gpt4 book ai didi

python datetime.now()不从包含文件的函数头返回更新的时间戳

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:45 25 4
gpt4 key购买 nike

对 datetime.now() 的调用目前返回与第一次调用相同的时间,即使在几个小时后调用也是如此。

我有以下代码。在第一个.py

#!/usr/bin/env python
import sys
import time
import datetime as dt
import fns_print as pr
import fns_time as tm

def main(argv):
pr.ts_print("STARTED")
# do a bunch of other stuff that takes 10+ seconds
pr.ts_print("Finished Download Pass")

if __name__ == "__main__":
main(sys.argv)

fns_print.py:

#!/usr/bin/env python
from __future__ import print_function
import fns_time as tme

def ts_print(string, **kwargs):
"""Print timestamped message to stdout and into log file"""
print("{}: {}".format(tme.strTimeSt(),string),**kwargs)
return True

fns_time.py

#!/usr/bin/env python
import time
from datetime import datetime, tzinfo, timedelta ## pip install datetime
from dateutil import tz
PST = tz.tzoffset("PST",-28800) # datetime.tzinfo.FixedOffset(-(8*60),"PST")
UTC = tz.tzutc() # UTC = tz.tzoffset("UTC",0)

def getCurTime(localTime = False):
"""get current time, by default in UTC. if localTime is True, it uses local system time"""
return datetime.now(tz=UTC) if not localTime else datetime.now(tz=tz.tzlocal())

def strTimeSt(t = datetime.now(tz=UTC), PSTConvert=False):
"""return a string representation of a datetime object. Uses UTC by default
Can also convert to PST with PSTConvert=True. Never converts to PDT."""
tf = t if not PSTConvert else t.astimezone(tz=PST)
return tf.strftime("%Y-%m-%d %H:%M:%S %Z (%z)")

两次调用的输出(一次运行):

2016-12-20 18:45:04 UTC (+0000): STARTED
2016-12-20 18:45:04 UTC (+0000): Finished Download Pass

上一次运行给出的两次都是 18:41:28

最佳答案

默认参数值 datetime.now(tz=UTC) 在定义函数时计算一次。如果你希望每次调用函数时都重新计算它,你需要将它移动到函数内部:

def strTimeSt(PSTConvert=False):
"""return a string representation of a datetime object. Uses UTC by default
Can also convert to PST with PSTConvert=True. Never converts to PDT."""
t = datetime.now(tz=UTC)
tf = t if not PSTConvert else t.astimezone(tz=PST)

return tf.strftime("%Y-%m-%d %H:%M:%S %Z (%z)")

如果您仍想允许传入日期时间,您可以将默认值设置为 None,然后检查 None 并仅在 None 被传递时调用 .now(),如下所示:

def strTimeSt(t=None, PSTConvert=False):
"""return a string representation of a datetime object. Uses UTC by default
Can also convert to PST with PSTConvert=True. Never converts to PDT."""
if t is None:
t = datetime.now(tz=UTC)
tf = t if not PSTConvert else t.astimezone(tz=PST)
return tf.strftime("%Y-%m-%d %H:%M:%S %Z (%z)")

关于python datetime.now()不从包含文件的函数头返回更新的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41249548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com