Converting a formatted time string to milliseconds

Kar*_*lik 7 python time datetime

I am trying to convert '2015-09-15T17:13:29.380Z' to milliseconds.

At first I used:

time.mktime(
  datetime.datetime.strptime(
    "2015-09-15T17:13:29.380Z",
    "%Y-%m-%dT%H:%M:%S.%fZ"
  ).timetuple()
)
Run Code Online (Sandbox Code Playgroud)

I got 1442330009.0 - with no microseconds. I think time.mktime rounds the number to the nearest second.

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)
Run Code Online (Sandbox Code Playgroud)

Is there a better way to do this and how do I work with the timezone?

jfs*_*jfs 5

您输入的时间是 UTC;time.mktime()除非您的本地时区始终是 UTC,否则在此处使用是不正确的。

有两个步骤:

  1. 将输入的 rfc 3339 时间字符串转换为表示 UTC 时间的 datetime 对象

    from datetime import datetime
    
    utc_time = datetime.strptime("2015-09-15T17:13:29.380Z",
                                 "%Y-%m-%dT%H:%M:%S.%fZ")
    
    Run Code Online (Sandbox Code Playgroud)

    你已经做到了。另请参阅将 RFC 3339 时间转换为标准 Python 时间戳

  2. 将 UTC 时间转换为以毫秒表示的 POSIX 时间

    from datetime import datetime, timedelta
    
    milliseconds = (utc_time - datetime(1970, 1, 1)) // timedelta(milliseconds=1)
    # -> 1442337209380
    
    Run Code Online (Sandbox Code Playgroud)

    对于适用于 Python 2.6-3+ 的版本,请参阅如何在 Python 中将日期时间对象转换为自纪元(unix 时间)以来的毫秒数?


pac*_*lik 1

不幸的是, 中没有毫秒timetuple。但是,您不需要timetuple。对于时间戳,只需调用

datetime.strptime(...).timestamp()
Run Code Online (Sandbox Code Playgroud)

至于时区,请查看tzinfo的参数datetime

编辑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
Run Code Online (Sandbox Code Playgroud)