I have some random dates with different timezones, they are in formats like this "07 Mar 2022 13:52:00 -0300"
, or they could be like this: "07 Mar 2022 11:12:00 -0700"
. I don’t know which timezone exactly they will be coming from. How can I convert all of them to UTC time "0000Z"
?
Advertisement
Answer
You can use standard module datetime for this.
Function strptime()
(string parsing time
) can convert string to object datetime
using matching pattern. For your examples works pattern '%d %b %Y %H:%M:%S %z'
Next you can use .astimezone(datetime.timezone.utc)
to convert to UTC
.
And later you can format string with strftime()
(string formatting time
) using again pattern '%d %b %Y %H:%M:%S %z'
(or you can skip %z
)
Minimal working code:
import datetime data = [ "07 Mar 2022 13:52:00 -0300", "07 Mar 2022 11:12:00 -0700", ] for item in data: print('before str:', item) dt = datetime.datetime.strptime(item, '%d %b %Y %H:%M:%S %z') print('before dt :', dt) dt = dt.astimezone(datetime.timezone.utc) print('after dt :', dt) print('after str:', dt.strftime('%d %b %Y %H:%M:%S %z')) print('---')
Result:
before str: 07 Mar 2022 13:52:00 -0300 before dt : 2022-03-07 13:52:00-03:00 after dt : 2022-03-07 16:52:00+00:00 after str: 07 Mar 2022 16:52:00 +0000 --- before str: 07 Mar 2022 11:12:00 -0700 before dt : 2022-03-07 11:12:00-07:00 after dt : 2022-03-07 18:12:00+00:00 after str: 07 Mar 2022 18:12:00 +0000 ---