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?
Asked
Active
Viewed 417 times
0

ZdaR
- 22,343
- 7
- 66
- 87

Tony Joseph
- 19
- 5
-
Please show the full code that produced the error. You may get an answer without it but it at least gives people a start. Thanks. – Garry Cairns Aug 02 '15 at 07:47
-
1are you sure it ends with `+00:00`? Does it happen to end with `+0000` instead? – Ozgur Vatansever Aug 02 '15 at 07:53
-
1Seems you are missing the Timezone, `%z`. However you might need to remove the colon there to make it work. edit: or it is as @ozgur assumes. – Sebastian Höffner Aug 02 '15 at 07:53
-
I got this datetime from django timezone. now(). It has a colon. I don't see a way to remove the colon. – Tony Joseph Aug 02 '15 at 07:56
-
Try `t = t[:len(t)-3]+t[len(t)-2:]` (it's called slicing) on your datetime string `t`, that should remove the colon. Then append `%z` to your format. – Sebastian Höffner Aug 02 '15 at 08:01
2 Answers
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