简体   繁体   中英

How to convert string datetime to UTC UNIX?

I have date in the as string in the following format: 202001010000

I am trying to convert this to UNIX format and get the result in UTC

I did:

import datetime

stime = "202001010000"

print(int(datetime.datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=datetime.timezone.utc).timestamp()))

and this is giving me the output in UNIX, but in CEST format.

With the above code I get: 1577836800 but I want the output to be 1577833200

What is the mistake I am doing?

You're setting time zone to UTC when converting to datetime. But since your input represents time in Germany you want a time zone that is active there. EX:

from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+, can use backports.zoneinfo for older versions

stime = "202001010000"
# stime represents time in Germany so we use time zone
time_zone = ZoneInfo('Europe/Berlin')

# to datetime, with tz set:
dtobj = datetime.strptime(stime, "%Y%m%d%H%M").replace(tzinfo=time_zone)

# unix time
ts = dtobj.timestamp()
print(ts)
# 1577833200.0

# back to datetime, again specify time zone
dtobj = datetime.fromtimestamp(ts, tz=time_zone)
print(dtobj)
# 2020-01-01 00:00:00+01:00

Note that if the input represents the same time zone your OS is configured to use, this works correctly without setting a time zone. But I think it's better to be explicit here, to avoid confusion if you eg run this script on a machine configured to use another time zone.

What you're trying to get is 7 hours behind and you cannot do that from your start date. You must push your start date back 1 day and push your hours forward 17. This code will work for you

import datetime

stime = "201912310000"

my_date = datetime.datetime.strptime(stime, "%Y%m%d%H%M")
my_date_utc = my_date.replace(hour=17)
my_timestamp = my_date_utc.timestamp()
print(int(my_timestamp))

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