chrisrhyno2003
chrisrhyno2003

Reputation: 4187

Parsing a time instant in python

I am relatively new to python. I have a timestamp of the format - 2016-12-04T21:16:31.265Z. It is of a type string. I want to know how can I parse the above timestamp in python.

I was looking through the datetime library, but seems like it accepts only floats. How do I get the time stamp parsed? I was trying to hunt for something like an equivalent of Instant (in java) for python?

Upvotes: 3

Views: 5832

Answers (2)

Ricardo Branco
Ricardo Branco

Reputation: 6079

To parse it according to your current timezone, using the format used by the Unix date command:

import re
from calendar import timegm
from datetime import datetime
from time import localtime, strptime, strftime

fmt = "%a %b %d %H:%M:%S %Z %Y"
ts = "2016-12-04T21:16:31.265Z"
strftime(fmt, localtime(timegm(strptime(re.sub("\.\d+Z$", "GMT", ts), '%Y-%m-%dT%H:%M:%S%Z'))))

Upvotes: -1

ju.
ju.

Reputation: 1096

import datetime
time_str = '2016-12-04T21:16:31.265Z'
time_stamp = datetime.datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(time_stamp)

Reference: https://docs.python.org/2/library/datetime.html; (8.1.7. strftime() and strptime() Behavior)

Upvotes: 4

Related Questions