在Python中,如何打印FULL ISO 8601时间戳,包括当前时区 [英] In Python, how to print FULL ISO 8601 timestamp, including current timezone

查看:94
本文介绍了在Python中,如何打印FULL ISO 8601时间戳,包括当前时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以ISO 8601格式打印完整的本地日期/时间,包括本地时区信息,例如:

  2007-04-05T12:30:00.0000-02:00 

我可以使用 datetime.isoformat()进行打印,如果我有正确的tzinfo对象-但是如何获取它?



注意,我停留在Python 2.5上,这可能会降低某些选项的可用性。

解决方案

我已经制定了自己的方法

  import datetime 
$

 b $ b#获取当前本地时间和utc时间
localnow = datetime.datetime.now()
utcnow = datetime.datetime.utcnow()

#计算时差以秒为单位
tzd = localnow-utcnow
secs = tzd.days * 24 * 3600 + tzd.seconds

#得到一个正数或负数前缀
prefix =' +'
,如果秒< 0:
前缀='-'
秒= abs(秒)

#打印带有时差的本地时间,格式正确的
后缀=%s% 02d:%02d%(前缀,秒/ 3600,秒/ 60%60)
现在= localnow.replace(microsecond = 0)
打印%s%s%(now.isoformat( ''),后缀)

这有点,但这似乎是获得认证的唯一可靠方法具有正确UTC偏移量的本地时间。欢迎提供更好的答案!


I need to print the FULL local date/time in ISO 8601 format, including the local timezone info, eg:

2007-04-05T12:30:00.0000-02:00

I can use datetime.isoformat() to print it, if I have the right tzinfo object - but how do I get that?

Note, I'm stuck at Python 2.5, which may reduce some availability of options.

解决方案

I've worked out my own way to do this, hopefully this will be useful to anyone else wanting to print useful timestamps in output files.

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)

This feels a little hacky, but seems the only reliable way to get a local time with the correct UTC offset. Better answers welcome!

这篇关于在Python中,如何打印FULL ISO 8601时间戳,包括当前时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆