[英]Converting a formatted time string to milliseconds
I am trying to convert '2015-09-15T17:13:29.380Z'
to milliseconds. 我想将
'2015-09-15T17:13:29.380Z'
转换为毫秒。
At first I used: 起初我用过:
time.mktime(
datetime.datetime.strptime(
"2015-09-15T17:13:29.380Z",
"%Y-%m-%dT%H:%M:%S.%fZ"
).timetuple()
)
I got 1442330009.0
- with no microseconds. 我得到
1442330009.0
- 没有微秒。 I think time.mktime
rounds the number to the nearest second. 我认为
time.mktime
将数字四舍五入到最接近的time.mktime
。
In the end I did: 最后我做了:
origTime = '2015-09-15T17:13:29.380Z'
tupleTime = datetime.datetime.strptime(origTime, "%Y-%m-%dT%H:%M:%S.%fZ")
microsecond = tupleTime.microsecond
updated = float(time.mktime(tupleTime.timetuple())) + (microsecond * 0.000001)
Is there a better way to do this and how do I work with the timezone ? 有没有更好的方法来做到这一点 ,我如何使用时区 ?
Your input time is in UTC; 您的输入时间是UTC; it is incorrect to use
time.mktime()
here unless your local timezone is always UTC. 除非您的本地时区始终为UTC,否则在此处使用
time.mktime()
是不正确的。
There are two steps: 有两个步骤:
Convert the input rfc 3339 time string into a datetime object that represents time in UTC 将输入rfc 3339时间字符串转换为表示UTC时间的日期时间对象
from datetime import datetime utc_time = datetime.strptime("2015-09-15T17:13:29.380Z", "%Y-%m-%dT%H:%M:%S.%fZ")
You've already done it. 你已经完成了。 See also Convert an RFC 3339 time to a standard Python timestamp
另请参阅将RFC 3339时间转换为标准Python时间戳
Convert UTC time to POSIX time expressed in milliseconds : 将UTC时间转换为以毫秒表示的POSIX时间 :
from datetime import datetime, timedelta milliseconds = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1) # -> 1442337209380
For a version that works on Python 2.6-3+, see How can I convert a datetime object to milliseconds since epoch (unix time) in Python? 对于适用于Python 2.6-3 +的版本,请参阅如何在Python中将epoch(unix时间)之后的datetime对象转换为毫秒?
Unfortunately, there is no miliseconds in timetuple
. 不幸的是,在
timetuple
没有毫秒。 However, you don't need timetuple
. 但是,您不需要
timetuple
。 For timestamp, just call 对于时间戳,只需致电
datetime.strptime(...).timestamp()
As for timezone, check out tzinfo
argument of datetime
. 至于时区,请查看
datetime
tzinfo
参数。
EDIT : tzinfo
编辑 :
tzinfo
>>> d
datetime.datetime(2015, 9, 15, 17, 13, 29, 380000)
>>> d.timestamp()
1442330009.38
>>> import pytz
>>> d.replace(tzinfo=pytz.timezone("US/Eastern")).timestamp()
1442355209.38
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.