How to convert timezone in number to UTC?

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"?

Upvotes: 0

Views: 1132

Answers (2)

furas
furas

Reputation: 142641

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
---

Upvotes: 2

Schnitte
Schnitte

Reputation: 1217

I would suggest to import datetime, then use the following method to convert your time stamps into datetime objects (where str is the time stamp as a string): time_stamp = datetime.strptime(str, "%d %b %Y") (where the parameter after str gives information on the formatting; for details see here: https://www.programiz.com/python-programming/datetime/strptime).

After that, you can use datetime.astimezone() to convert this into another time zone.

Upvotes: 0

Related Questions