Python:将字符串转换为具有微秒的时间戳 [英] Python: Converting string to timestamp with microseconds

查看:2880
本文介绍了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()

使用本地时间纪元是非常有意义的,因为您有一个天真的(不是时区感知的)datetime值。根据您当地时区的历史记录,此方法可能不正确,请参阅 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:将字符串转换为具有微秒的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆