2

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.

Mikasa
  • 321
  • 7
  • 16
  • 1
    What about `parser.parse("Thu Dec 10 13:25:26 UTC 2020")`? Works fine for me... You could use Python's `strptime` as well but that won't parse `UTC` to `tzinfo=timezone.utc`. – FObersteiner Feb 08 '21 at 10:30
  • Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – FObersteiner Feb 08 '21 at 10:32

1 Answers1

3

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
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
  • it should also be noted that the datetime object returned by `strptime` is naive, i.e. has no timezone information. Since the input is UTC and Python uses local time by default, this is error-prone (see also my comment on the question). – FObersteiner Feb 08 '21 at 13:17