Reputation: 19
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?
Upvotes: 0
Views: 440
Reputation: 1944
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)
Upvotes: 0
Reputation: 18070
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
Upvotes: 1