Reputation: 21
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
Upvotes: 1
Views: 442
Reputation: 21
This is now solved based on the comments from MrFuppes [1, 2]:
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 e.g. by
transaction_time_parsed = transaction_time_parsed.replace(tzinfo=timezone.utc)
with timezone being imported from the datetime module.See also the docs on naive vs. aware datetime.
Upvotes: 1