简体   繁体   中英

How to format ISO date time to UTC date time?

As the title already tells, how can I (easily) format a ISO date time to a UTC date time in Bash?

Actual:

➜  ~ echo $tmp
"2020-03-18T11:19:00+01:00"

Expected:

"2020-03-18T10:19:00+00:00"

If using GNU/Linux based systems try the following:

date -u -d "$tmp" -Is

This will read in your date and print it to the ISO8601 format with seconds as the precision (matching your desired output)

Created a Python-script and that worked for me!

(The timezone is hardcoded to "Europe/Amsterdam" .)

➜  ~ python3 convert_datetime_to_utc.py "2020-12-31T12:00:00+02:00"
2020-12-31T11:00:00+00:00

Content of convert_datetime_to_utc.py file:

#!/usr/bin/python3

import sys, pytz, datetime

if len(sys.argv) != 2:
    sys.exit('Datetime not found as cmd line arg (Example: \'python3 convert_date_time_to_utc.py 2020-12-31T23:59:00+01:00\')')
dt_raw=sys.argv[1]

if len(dt_raw) < 19:
    sys.exit('Incorrect date time format (Example: \'2020-12-31T23:59:00+01:00\')')
dt = dt_raw[0:19]

local = pytz.timezone ("Europe/Amsterdam")
naive = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
utc_dt_formatted = utc_dt.strftime("%Y-%m-%dT%H:%M:%S+00:00")

print(utc_dt_formatted)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM