简体   繁体   English

将UTC时间转换为Epoch格式

[英]Converting a UTC Time to Epoch format

I'm trying to convert a specific UTC time & date to seconds since the Epoch; 我正在尝试将特定的UTC时间和日期转换为自Epoch以来的秒数; however, I have not been able to figure out how to do this since I am not in the UTC time zone. 但是,由于我不在UTC时区,我无法弄清楚如何做到这一点。

I tried using the datetime module to convert a date & time to seconds since the epoch, but python has been using my system's local time so the returned value is off by 7 hours. 我尝试使用datetime模块将日期和时间转换为自纪元以来的秒数,但是python一直在使用我系统的本地时间,因此返回的值关闭了7个小时。 I understand that I could simply subtract 7*60 so that it would work in my time zone; 我明白我可以简单地减去7 * 60,这样它就能在我的时区里工作; however, I need this to work in multiple time zones without hardcoding the time change into my program. 但是,我需要在多个时区工作,而不会将时间更改硬编码到我的程序中。

This works except it uses the system time (MST), but I am looking for a solution that is specifically UTC time. 这工作除了它使用系统时间(MST),但我正在寻找一个特定的UTC时间的解决方案。 Note the variables defined here represent an example of a time in UTC that I am trying to convert to seconds since the epoch. 请注意,此处定义的变量表示我尝试将UTC转换为自纪元以来的秒数的UTC时间示例。

import datetime

year=2019
month=5
day=9
hour=21
minute=45

Time=datetime.datetime(year, month, day, hour, minute).timestamp()
print(Time)

Output: 输出:

1557463500.0

Desired output (7 hours earlier): 期望的输出(7小时前):

1557438300.0
import datetime

year=2019
month=5
day=9
hour=21
minute=45

e = datetime.datetime(1970, 1, 1, 0, 0)
t = datetime.datetime(year, month, day, hour, minute)
print((t-e).total_seconds())

You can caclulate the timestamp of epoch date using datetime.datetime.utcfromtimestamp(0).timestamp() and then subtract your current timestamp from it 你可以使用datetime.datetime.utcfromtimestamp(0).timestamp()来计算纪元日期的时间戳,然后从中减去你当前的时间戳。

import datetime

year=2019
month=5
day=9
hour=21
minute=45

#Date timestamp
dt_timestamp=datetime.datetime(year, month, day, hour, minute).timestamp()

#Epoch timestamp
epoch = datetime.datetime.utcfromtimestamp(0).timestamp()

#Epoch
print(dt_timestamp-epoch)

The output will be 输出将是

1557438300.0

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

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