简体   繁体   中英

Converting a formatted time string to milliseconds

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()
)

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)

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

Your input time is in UTC; it is incorrect to use time.mktime() here unless your local timezone is always UTC.

There are two steps:

  1. Convert the input rfc 3339 time string into a datetime object that represents time in 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

  2. Convert UTC time to POSIX time expressed in milliseconds :

     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?

Unfortunately, there is no miliseconds in timetuple . However, you don't need timetuple . For timestamp, just call

datetime.strptime(...).timestamp()

As for timezone, check out tzinfo argument of datetime .

EDIT : 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM