3

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?

chrisrhyno2003
  • 3,906
  • 8
  • 53
  • 102

2 Answers2

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

roganjosh
  • 12,594
  • 4
  • 29
  • 46
ju.
  • 1,016
  • 1
  • 13
  • 34
-1

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'))))
Ricardo Branco
  • 5,740
  • 1
  • 21
  • 31