【script】python自定义时间格式的几种情况

格式一(中式)

结果:2020-01-03 22:11:22

import time
nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(nowtime)

 

格式二(英式)

结果:Fri Jan 03 22:14:46 2020

import time
nowtime = time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
print(nowtime)

 

格式三(无前置0)

结果:2020年1月3日 22:7:52

import datetime
time_tuple = datetime.datetime.now().timetuple()
nowtime = str(time_tuple.tm_year) + '年' + str(time_tuple.tm_mon) + '月' + str(time_tuple.tm_mday) + '日 ' +str(time_tuple.tm_hour) + ':' +str(time_tuple.tm_min) + ':' + str(time_tuple.tm_sec)
print(nowtime)

 

附:时间相减

import datetime
time_task = "2020-01-05 10:40:33"   # str
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')   # 获取当前时间,为 2020-01-08 01:41:56, str
datetime_task = datetime.datetime.strptime(time_task, '%Y-%m-%d %H:%M:%S')  # 转化为datetime格式
datetime__now = datetime.datetime.strptime(time_now, '%Y-%m-%d %H:%M:%S')  # datetime
print((datetime__now-datetime_task).days) # 输出天数之差, 2

 

你可能感兴趣的:(python编程)