0

I have a datetime in the format 2015-08-02 07:06:46.022111+00:00. When I use strptime() on this with format "%Y-%m-%d %H:%M:%S.%f" I got an error 'ValueError unconverted data remains: +00:00'. Is there any way to include +00:00 part to the format string?

ZdaR
  • 22,343
  • 7
  • 66
  • 87

2 Answers2

1

I really like the python-dateutil module. With this module parsing datetime is just as simple as that:

>>> from dateutil import parser
>>> parser.parse('2015-08-02 07:06:46.022111+00:00')
datetime.datetime(2015, 8, 2, 7, 6, 46, 22111, tzinfo=tzutc())

You can install it with pip:

pip install python-dateutil
sobolevn
  • 16,714
  • 6
  • 62
  • 60
  • Yeah, `dateutil` seems to be the preferred way of converting ISO 8601 formatted dates back into `datetime` objects. See http://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object – lemonhead Aug 02 '15 at 08:12
0

You can use slicing to get rid of the colon and add %z to also specify the timezone:

import datetime
timestring = '2015-08-02 07:06:46.022111+00:00'
timestring = timestring[:len(timestring)-3]+timestring[len(timestring)-2:]
dtformat = '%Y-%m-%d %H:%M:%S.%f%z'
dt = datetime.datetime.strptime(timestring, dtformat)

dt is then:

datetime.datetime(2015, 8, 2, 7, 6, 46, 22111, tzinfo=datetime.timezone.utc)
Sebastian Höffner
  • 1,864
  • 2
  • 26
  • 37