Python:用微秒将字符串转换为时间戳

时间:2023-04-17
本文介绍了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

这篇关于Python:用微秒将字符串转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:windows下用python修改文件创建/访问/写入时间戳 下一篇:在 Python 中合并和排序日志文件

相关文章