問題描述
我想將字符串日期格式轉換為以微秒為單位的時間戳我嘗試以下但未給出預期結果:
I would like to convert string date format to timestamp with microseconds I try the following but not giving expected result:
"""input string date -> 2014-08-01 04:41:52,117
expected result -> 1410748201.117"""
import time
import datetime
myDate = "2014-08-01 04:41:52,117"
timestamp = time.mktime(datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple())
print timestamp
> 1410748201.0
毫秒去哪兒了?
推薦答案
時間元組中沒有微秒組件的槽:
There is no slot for the microseconds component in a time tuple:
>>> import time
>>> import datetime
>>> myDate = "2014-08-01 04:41:52,117"
>>> datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f").timetuple()
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=1, tm_hour=4, tm_min=41, tm_sec=52, tm_wday=4, tm_yday=213, tm_isdst=-1)
您必須手動添加:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> time.mktime(dt.timetuple()) + (dt.microsecond / 1000000.0)
1406864512.117
您可以遵循的另一種方法是生成 timedelta()
對象 相對于紀元,然后使用 timedelta.total_seconds()
方法:
The other method you could follow is to produce a timedelta()
object relative to the epoch, then get the timestamp with the timedelta.total_seconds()
method:
epoch = datetime.datetime.fromtimestamp(0)
(dt - epoch).total_seconds()
本地時間紀元的使用是經過深思熟慮的,因為您有一個幼稚的(不是時區感知的)日期時間值.此方法可能根據您當地時區的歷史記錄不準確,但請參閱 JF塞巴斯蒂安的評論.您必須先使用本地時區將原始日期時間值轉換為可識別時區的日期時間值,然后再減去可識別時區的紀元.
The use of a local time epoch is quite deliberate since you have a naive (not timezone-aware) datetime value. This method can be inaccurate based on the history of your local timezone however, see J.F. Sebastian's comment. You'd have to convert the naive datetime value to a timezone-aware datetime value first using your local timezone before subtracting a timezone-aware epoch.
因此,堅持 timetuple()
+ 微秒的方法更容易.
As such, it is easier to stick to the timetuple()
+ microseconds approach.
演示:
>>> dt = datetime.datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
>>> epoch = datetime.datetime.fromtimestamp(0)
>>> (dt - epoch).total_seconds()
1406864512.117
這篇關于Python:用微秒將字符串轉換為時間戳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!