是否有time.gmtime()的反函数,将UTC元组从纪元解析为秒?

2024-05-18 15:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

python的时间模块似乎有点随意。例如,这里有一个方法列表,来自docstring:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone

看看localtime()及其逆mktime(),为什么gmtime()没有逆?

附加问题:你会给这个方法起什么名字?你将如何实施它?


Tags: theto方法inconvertstringreturntime
3条回答

我只是Python的新手,但我的方法是这样的。

def mkgmtime(fields):
    now = int(time.time())
    gmt = list(time.gmtime(now))
    gmt[8] = time.localtime(now).tm_isdst
    disp = now - time.mktime(tuple(gmt))
    return disp + time.mktime(fields)

在这里,我提议的函数名也是。:-)每次重新计算disp很重要,以防夏时制值发生变化等。(Jython需要转换回元组。CPython似乎并不需要它。)

这是super ick,因为time.gmtime总是将DST标志设置为false。不过,我讨厌密码。一定有更好的办法。可能还有一些角落的案子我还没有拿到。

实际上有一个逆函数,但出于某种奇怪的原因,它位于calendar模块:calendar.timegm()中。我列出了这个answer中的函数。

我一直认为时间和日期时间模块有点不连贯。不管怎样,这是mktime的倒数

import time
def mkgmtime(t):
    """Convert UTC tuple to seconds since Epoch"""
    return time.mktime(t)-time.timezone

相关问题 更多 >

    热门问题