Skip to main content
 首页 » 编程设计

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

2025年05月04日15findumars

对 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)")