Karl Stulik
Karl Stulik

Reputation: 990

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?

Upvotes: 9

Views: 16772

Answers (2)

pacholik
pacholik

Reputation: 8972

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

Upvotes: 1

jfs
jfs

Reputation: 414215

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?

Upvotes: 9

Related Questions