Python关于时间日期有两个库datetime和time,于是我们要在四种格式之间转换:
datetime.datetime对象 datetime.datetime.now()
time.struct_time对象 time.localtime()
字符串 "2010-12-04T10:30:53"
时间戳 1291433453 (一般我们不关心微秒)
列一下它们的转换方法:
可以看出,Python没有提供直接的time.struct_time对象到datetime.datetime对象的转换,也没有直接提供datetime.datetime对象到时间戳的转换。另外,Python的两个strftime ,strptime中都没有时间戳的格式化符号。
对time.struct_time对象到datetime.datetime对象的转换,很容易想到通过字符串形式过渡一下:
更好的方式应该是这样
对于datetime.datetime对象到时间戳的转换,常用做法是通过time.struct_time对象过渡:
坏处是要同时用到datetime和time两个模块。
其实可以在datetime内部解决,现在给一个三种格式转为时间戳的方法: