【留备自查】python time/datetime模块时间格式转换

Python time, datetime模块常用方法

1、使用time模块,获取当前时间戳
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import time
time.time()
Out[3]: 1546046383.663

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 

2、将一个时间戳转化为结构化的元组  struct_time
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
time.localtime(1546046383.663)
Out[4]: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=29, tm_hour=9, tm_min=19, tm_sec=43, tm_wday=5, tm_yday=363, tm_isdst=0)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


3、已知时间戳,格式化字符串形式的时间输出
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(1546046383.663))
Out[5]: '2018-12-29 09:19:43'

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


4、直接格式化输出当前时间
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
time.strftime('%Y-%m-%d %H:%M:%S')
Out[6]: '2018-12-29 09:27:50'

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


5、获取毫秒级精度的时间,使用datetime模块
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import datetime
datetime.datetime.now()
Out[8]: datetime.datetime(2018, 12, 29, 9, 30, 38, 269000)
datetime.datetime.now().isoformat()
Out[9]: '2018-12-29T09:31:11.487000'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
等效方法
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
datetime.datetime.today().isoformat()
Out[16]: '2018-12-29T09:38:19.502000'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


6、从时间戳转到格式化时间字符串,精确到毫秒
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
Out[12]: '2018-12-29 09:33:06.735000'

datetime.datetime.fromtimestamp(1546046383.663).strftime('%Y-%m-%d %H:%M:%S.%f')
Out[13]: '2018-12-29 09:19:43.663000'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


7、将结构化的元组时间格式转为时间戳格式, time.maketime(元组类型时间)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
time.mktime(datetime.datetime.now().timetuple())
Out[21]: 1546047923.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


8、字符串格式的时间提取,转为结构化元组格式,进而转化为时间戳格式。 strptime(时间字符串, 时间格式)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
time.strptime('2018-12-29 09:49:36','%Y-%m-%d %H:%M:%S')
Out[22]: time.struct_time(tm_year=2018, tm_mon=12, tm_mday=29, tm_hour=9, tm_min=49, tm_sec=36, tm_wday=5, tm_yday=363, tm_isdst=-1)

time.mktime(time.strptime('2018-12-29 09:49:36','%Y-%m-%d %H:%M:%S'))
Out[23]: 1546048176.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

posted @ 2018-12-29 10:29  水一年  阅读(1575)  评论(0编辑  收藏  举报