Python:用微秒将字符串转换为时间戳
问题描述
我想将字符串日期格式转换为以微秒为单位的时间戳我尝试以下但未给出预期结果:
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
相关文章