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:
JavaScript
x
20
20
1
import datetime
2
3
data = [
4
"07 Mar 2022 13:52:00 -0300",
5
"07 Mar 2022 11:12:00 -0700",
6
]
7
8
for item in data:
9
print('before str:', item)
10
11
dt = datetime.datetime.strptime(item, '%d %b %Y %H:%M:%S %z')
12
print('before dt :', dt)
13
14
dt = dt.astimezone(datetime.timezone.utc)
15
print('after dt :', dt)
16
17
print('after str:', dt.strftime('%d %b %Y %H:%M:%S %z'))
18
19
print('---')
20
Result:
JavaScript
1
11
11
1
before str: 07 Mar 2022 13:52:00 -0300
2
before dt : 2022-03-07 13:52:00-03:00
3
after dt : 2022-03-07 16:52:00+00:00
4
after str: 07 Mar 2022 16:52:00 +0000
5
---
6
before str: 07 Mar 2022 11:12:00 -0700
7
before dt : 2022-03-07 11:12:00-07:00
8
after dt : 2022-03-07 18:12:00+00:00
9
after str: 07 Mar 2022 18:12:00 +0000
10
---
11