简体   繁体   中英

Convert UTC datetime to UTC epoch

I'm pulling a transaction date from an API in UTC time.

My goal is to convert this UTC datetime to UTC epoch time.

At the moment, it looks like.timestamp() changes the timezone of the datetime to my local timezone.

Any insight is appreciated!

INPUT:
# Get timestamp of transaction from events - (Note: events = data from API request)
transaction_time = event['transaction']['timestamp'] 
# Print transaction time value - (Data Type: str)
print("Transaction time:", transaction_time)

# Parse transaction_time
transaction_time_parsed = parser.parse(str(transaction_time))
# Print transaction_time_parsed value - (Data Type: datetime.datetime)
print("Parsed transaction time:", transaction_time_parsed)

# Convert transaction_time_parsed to epoch time and remove decimal
transaction_epoch_time = format((parser.parse(str(transaction_time)).timestamp()), '.0f')
# Print transaction_epoch_time value - (Data Type: str)
print("After .timestamp() & epoch conversion:", transaction_epoch_time)

OUTPUT:
Transaction time: 2021-11-11T23:12:19
Parsed transaction time: 2021-11-11 23:12:19
After .timestamp() & epoch conversion: 1636690339

1636690339 converts to:

GMT: 2021-11-12 4:12:19

Your time zone: 2021-11-11 23:12:19 GMT-05:00

See @MrFuppes comment for the answer:

If you don't set a time zone to a Python datetime object, it will assume that it represents local time. This is why your Unix time is off by your local time's UTC offset. So set UTC eg by transaction_time_parsed = transaction_time_parsed.replace(tzinfo=timezone.utc) with timezone being imported from the datetime module. – MrFuppes 11 mins ago

See also the docs on naive vs. aware datetime – MrFuppes 9 mins ago

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