我知道这在其他地方一定是一个很好的问题,但我在 SO 上看到的大多数问题看起来都在朝着相反的方向发展。我了解如何将 FROM time.time()
转换为人类可读的日期时间格式,如下所示:
>>> import time, datetime
>>> thetime = time.time()
>>> thetime
1375289544.41976
>>> datetime.datetime.fromtimestamp(thetime).strftime("%Y-%m-%d %H:%M:%S")
'2013-07-31 12:51:08'
反方向的作用是什么?
>>> thetime = '2013-07-30 21:23:14.744643'
>>> time.strptime(thetime, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: .744643
我想从字符串转到自纪元格式以来的秒数。
更新
这就是我正在使用的,但它看起来不够优雅——必须已经有一个函数可以做到这一点,对吧?
def datetostamp(x):
thetime = x.split('.')
return(time.mktime(time.strptime(thetime[0], "%Y-%m-%d %H:%M:%S")) + float('.'+thetime[1]))
>>> thetime = '2013-07-30 21:23:14.744643'
>>> datetostamp(thetime)
1375233794.744643
更新 2
也许更简单,我只是错过了几分之一秒的格式代码?
最佳答案
您错过了几分之一秒的格式。
time.strptime(thetime, "%Y-%m-%d %H:%M:%S.%f")
关于python - 字符串日期时间格式为 time() python 中的 unix 时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17976447/