Skip to content Skip to sidebar Skip to footer

Converting String To Datetime In Python Using Strptime

I'm trying to convert the following String to datetime object in Python. datetime_object = datetime.strptime('Sat, 26 Nov 2016 15:17:00 +0000', '%a, %b %d %Y %H:%c %z') I get the

Solution 1:

You're almost there, but there were a few errors in the directives you were using. Try:

datetime_object = datetime.strptime('Sat, 26 Nov 2016 15:17:00 +0000', '%a, %d %b %Y %H:%M:%S %z')

>>> datetime_object
datetime.datetime(2016, 11, 26, 15, 17, tzinfo=datetime.timezone.utc)

Solution 2:

%c is defined as Locale’s appropriate date and time representation. This means that %c is in fact a macro for the current locale's format string and thus is meant to be used by itself.

In the case of en_US, your format string expands to '%a, %b %d %Y %H:%a %b %d %H:%M:%S %Y %z' As you can see, %a is in position 1 as well as position 6.

Writing correct format strings requires quite a bit of careful book-keeping.


Post a Comment for "Converting String To Datetime In Python Using Strptime"