xor*_*yst 5 python datetime python-2.5
我需要以 ISO 8601 格式打印完整的本地日期/时间,包括本地时区信息,例如:
2007-04-05T12:30:00.0000-02:00
Run Code Online (Sandbox Code Playgroud)
datetime.isoformat()如果我有正确的 tzinfo 对象,我可以用来打印它 - 但我如何得到它?
请注意,我坚持使用 Python 2.5,这可能会降低某些选项的可用性。
我已经找到了自己的方法来做到这一点,希望这对其他想要在输出文件中打印有用时间戳的人有用。
import datetime
# get current local time and utc time
localnow = datetime.datetime.now()
utcnow = datetime.datetime.utcnow()
# compute the time difference in seconds
tzd = localnow - utcnow
secs = tzd.days * 24 * 3600 + tzd.seconds
# get a positive or negative prefix
prefix = '+'
if secs < 0:
prefix = '-'
secs = abs(secs)
# print the local time with the difference, correctly formatted
suffix = "%s%02d:%02d" % (prefix, secs/3600, secs/60%60)
now = localnow.replace(microsecond=0)
print "%s%s" % (now.isoformat(' '), suffix)
Run Code Online (Sandbox Code Playgroud)
这感觉有点老套,但似乎是获取具有正确 UTC 偏移量的当地时间的唯一可靠方法。欢迎更好的答案!
| 归档时间: |
|
| 查看次数: |
2680 次 |
| 最近记录: |