简体   繁体   English

将 UTC 日期时间转换为 UTC 纪元

[英]Convert UTC datetime to UTC epoch

I'm pulling a transaction date from an API in UTC time.我正在从 UTC 时间的 API 中提取交易日期。

My goal is to convert this UTC datetime to UTC epoch time.我的目标是将此 UTC 日期时间转换为 UTC 纪元时间。

At the moment, it looks like.timestamp() changes the timezone of the datetime to my local timezone.目前,看起来 .timestamp() 将日期时间的时区更改为我的本地时区。

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: 1636690339 转换为:

GMT: 2021-11-12 4:12:19格林威治标准时间:2021-11-12 4:12:19

Your time zone: 2021-11-11 23:12:19 GMT-05:00您的时区:2021-11-11 23:12:19 GMT-05:00

See @MrFuppes comment for the answer:请参阅@MrFuppes 评论以获取答案:

If you don't set a time zone to a Python datetime object, it will assume that it represents local time.如果您没有将时区设置为 Python 日期时间 object,它将假定它代表本地时间。 This is why your Unix time is off by your local time's UTC offset.这就是为什么您的 Unix 时间与您的本地时间的 UTC 偏移量不同的原因。 So set UTC eg by transaction_time_parsed = transaction_time_parsed.replace(tzinfo=timezone.utc) with timezone being imported from the datetime module.因此,例如通过 transaction_time_parsed = transaction_time_parsed.replace(tzinfo=timezone.utc) 设置 UTC,并从 datetime 模块导入时区。 – MrFuppes 11 mins ago – MrFuppes 11 分钟前

See also the docs on naive vs. aware datetime – MrFuppes 9 mins ago另请参阅有关 naive vs. aware datetime 的文档 – MrFuppes 9 分钟前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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