1

I have the timestamp format such as "2014-01-06T00:39:45.001+0000" but I don't know exactly what this timestamp format is. So I can't convert it to datetime as I desired.

How can I convert it with Python?

Tan Viet
  • 1,873
  • 4
  • 22
  • 35
  • @tback: or more specifically it is a profile of ISO 8601 described in [rfc 3339](http://tools.ietf.org/search/rfc3339) (+/- ":" in time offset) – jfs Jan 07 '14 at 17:30

2 Answers2

4

Use dateutil.parser.parse:

>>> import dateutil.parser
>>> dateutil.parser.parse("2014-01-06T00:39:45.001+0000")
datetime.datetime(2014, 1, 6, 0, 39, 45, 1000, tzinfo=tzutc())
falsetru
  • 336,967
  • 57
  • 673
  • 597
3

You can parse dates and times in arbitrary formats using datetime.strptime(date_string, format), with the grammar for defining format presented here.

In this case:

 format = "%Y-%m-%dT%H:%M:%S.%f%z"

Note: %z is not supported before Python 3.2 for the .strptime() method.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
  • It's in [the docs for 2.7.x](http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior). – jonrsharpe Jan 07 '14 at 17:47
  • I guess I don't! You are right, but I can't see a reference to that behaviour in the docs; note (5) for `%z` doesn't mention it, although other notes mention the difference. I will edit my answer. – jonrsharpe Jan 07 '14 at 18:04