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

时间:2016-12-20 19:08:28

标签: python datetime include

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

我有以下代码。在first.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):完成下载通行证

之前的比赛两次都是18:41:28

1 个答案:

答案 0 :(得分:7)

默认参数值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)")

如果您仍然希望允许传入日期时间,则可以将默认值设置为“无”,然后选中“无”,如果未通过则仅调用.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)")