Convert date of format "Thu Dec 10 13:25:26 UTC 2020" to datetime python

Viewed 223

I have a date string with format "Thu Dec 10 13:25:26 UTC 2020". I want to convert this to UTC datetime in python. How can I do that?

I had a string of format "2021-02-02T21:39:35-08:00" and I was able to convert this using the following code

from datetime import timezone
from dateutil import parser
parser.isoparse("2021-02-02T21:39:35-08:00").astimezone(timezone.utc)
>>datetime.datetime(2021, 2, 3, 5, 39, 35, tzinfo=datetime.timezone.utc)

I am not sure how to do that for the format (Thu Dec 10 13:25:26 UTC 2020) above.

1 Answers

You can use strptime from datetime.datetime with desire format, or can use parser from dateutil try:

from datetime import datetime
from dateutil import parser

date_str = 'Thu Dec 10 13:25:26 UTC 2020'

datetime_object = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y')

print(datetime_object)

print(parser.parse(date_str))

output:

2020-12-10 13:25:26
2020-12-10 13:25:26+00:00
Related