简体   繁体   中英

How to convert the local time into utc time in python

I am trying to convert the local time into UTC time. But getting the below error.

Error: an integer is required (got type str)

from datetime import datetime

starts_date = '2021-07-30 09:30:00'(timestamp without time zone)

ts = starts_date
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()

Be sure that datetime is imported correctly as from datetime import datetime . Can be a bit confusing but the method utcfromtimestamp belongs to datetime.datetime and not datetime itself.

Here is a working example to convert a timestamp of (now) to a UTC timestamp.

from datetime import datetime as dt

# Create a timestamp object for now.
ts = dt.timestamp(dt.now())

# Convert now to a UTC timestamp.
dt.utcfromtimestamp(ts).timestamp()

>>> 1627637013.657752

datetime.utcfromtimestamp() takes an integer that represent the amount of seconds passed since January 1st 1970. This means with

from datetime import datetime as dt
print(dt.utcfromtimestamp(0))

you get

1970-01-01 00:00:00

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