I have a variable
date_1 = "2023-04-14T09:57:40-04:00"
how to convert to proper format - 2023-04-14T05:57:40Z
Expected ouput - "2023-04-14T05:57:40Z"
I have a variable
date_1 = "2023-04-14T09:57:40-04:00"
how to convert to proper format - 2023-04-14T05:57:40Z
Expected ouput - "2023-04-14T05:57:40Z"
Essentially, you're looking to convert a date/time string with a UTC offset to UTC. You can do that like
from datetime import datetime, timezone
date_1 = "2023-04-14T09:57:40-04:00"
utc = datetime.fromisoformat(date_1).astimezone(timezone.utc)
print(utc)
# 2023-04-14 13:57:40+00:00
print(utc.isoformat().replace("+00:00", "Z"))
# 2023-04-14T13:57:40Z
Notes:
replacePlease refer to the other answer posted, this one does not properly convert UTC.
import datetime
import calendar
date_1 = '2023-04-14T09:57:40-04:00'
datex, timez=date_1[0:-6], date_1[-6:]
timed = datetime.datetime.strptime(datex, "%Y-%m-%dT%H:%M:%S")
timez = datetime.datetime.strptime(timez.replace(':',''), "%z")
output=datetime.datetime.fromtimestamp(calendar.timegm(timed.timetuple()), tz=timez.tzinfo).strftime("%Y-%m-%dT%H:%M:%SZ")
Code first splits datetime (datex) and timezone (timez). Converts datex to datetime.datetime then epoch, and convert timez to datetime. Finally converting datex to UTC time based off current timezone, then formats the datetime.datetime object to string.
Previous answer (not working)
import datetime
import calendar
date_1 = "2023-04-14T09:57:40-04:00"
timed = datetime.datetime.strptime(date_1, "%Y-%m-%dT%H:%M:%S%z")
output=datetime.datetime.fromtimestamp(calendar.timegm(timed.timetuple()), tz=timed.tzinfo).strftime("%Y-%m-%dT%H:%M:%SZ")
It's a bit long, but it should work!
The program first converts the date_1 to a datetime.datetime object, then it converts it to epoch time, from which it converts this epoch time to the UTC timezone, and finally formats the epoch time to the output string.
Please let me know if this works for you.