【问题标题】:Epoch time is one hour out from UTC, should be UTC+1纪元时间比 UTC 差一小时,应该是 UTC+1
【发布时间】:2014-04-11 09:47:30
【问题描述】:

我编写了一个模块,可以生成特定时间发生的事件的百分比概率。我的数据库有一个生成事件的时间戳。我正在将 y-m-d h-m-s 格式的时间戳转换为纪元时间。我得到的纪元时间是 UTC (GMT) 时间,而我的时区是 GMT + 1。

一个例子如下:

我的第一个数据库条目是在 10:13:36,其纪元时间为 1397211216,当我尝试从我的代码中获取此条目的纪元时间时,返回的纪元时间为 1397207617(09:13: 36).我的代码在下面,我知道如何定义纪元时间存在问题,但我不知道如何更改它以获得正确的时间。

def getPercentageDuringTime(dbName, sensorType, beginningTime, endTime):
    count = 0
    reading = [i [1]for i in cur.execute("SELECT * FROM " + dbName + " WHERE sensor = '" + sensorType + "' ")] 
    readingtime = [i [2] for i in cur.execute("SELECT * FROM " + dbName + " WHERE sensor = '" + sensorType + "' ")] 
    for i in range(len(reading)):
        pattern = '%Y-%m-%d %H:%M:%S'
        epoch = int(time.mktime(time.strptime(readingtime[i], pattern)))
        if ((epoch >= beginningTime) and (epoch <= endTime)):
            count = count + 1
    percentage = count / (len(reading)) * 100

    print (epoch)
    return percentage

print (getPercentageDuringTime('event4312593', 'sound', 1397207617, 1397207616))

【问题讨论】:

标签: python datetime time epoch


【解决方案1】:

time.mktime() functiontime.localtime() 的倒数,因此您的解析时间被解释为 UTC,然后移动到您的本地时区。

您需要在这里使用的是 time.gmtime() 的倒数,它被隐藏在不同的模块中:calendar.timegm() function

>>> import time, calendar
>>> sample = '2014-04-11 10:13:36'
>>> int(time.mktime(time.strptime(sample, pattern)))
1397207616
>>> int(calendar.timegm(time.strptime(sample, pattern)))
1397211216

考虑使用datetime 模块,而不是使用UNIX 纪元的偏移量;它可以让您处理时间戳而不必担心时区问题,这非常适合您的需求:

>>> import datetime
>>> datetime.datetime.strptime(sample, pattern)
datetime.datetime(2014, 4, 11, 10, 13, 36)

如果您必须传入时间戳(自 UNIX 纪元以来的秒数),您可以使用 datetime.datetime.fromtimestamp() 将其转换为日期时间对象:

>>> datetime.datetime.fromtimestamp(1397207617)
datetime.datetime(2014, 4, 11, 10, 13, 37)

通过解释机器本地时区中的值,为您提供 datetime 对象。

【讨论】:

  • 太棒了,.timegm 做得很好!感谢您的帮助
猜你喜欢
  • 2017-08-23
  • 2021-12-31
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 2019-02-16
  • 2019-09-26
  • 2013-04-24
  • 2016-07-26
相关资源
最近更新 更多