以特殊格式打印当前UTC日期时间

时间:2014-10-04 12:59:15

标签: python datetime python-2.6 datetime-format

很简单,但我是一个蟒蛇新手。我正在尝试使用特殊格式打印当前的UTC日期和时间:

Python 2.6.6

import datetime, time
print time.strftime("%a %b %d %H:%M:%S %Z %Y", datetime.datetime.utcnow())

TypeError: argument must be 9-item sequence, not datetime.datetime

3 个答案:

答案 0 :(得分:12)

time.strftime()只需time.struct_time-like time tuples个,而非datetime个对象。

改为使用datetime.strftime() method

>>> import datetime
>>> datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
'Sat Oct 04 13:00:36  2014'

但请注意,在Python 2.6中没有包含时区对象,因此%Z没有打印任何内容; datetime.datetime.utcnow()返回的对象是天真(没有与之关联的时区对象)。

由于您使用的是utcnow(),因此请手动添加时区:

>>> datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")
'Sat Oct 04 13:00:36 UTC 2014'

答案 1 :(得分:2)

utcnow()返回一个对象;你应该在那个对象上调用.strftime

>>> datetime.datetime.utcnow()
datetime.datetime(2014, 10, 4, 13, 0, 2, 749890)
>>> datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
'Sat Oct 04 13:00:16  2014'

或者将对象作为datetime.datetime.strftime第一个参数传递:

>>> type(datetime.datetime.utcnow())
<class 'datetime.datetime'>
>>> datetime.datetime.strftime(datetime.datetime.utcnow(), "%a %b %d %H:%M:%S %Z %Y")
'Sat Oct 04 13:00:16  2014'

答案 2 :(得分:1)

要以UTC格式打印当前时间而不更改格式字符串,您可以define UTC tzinfo class yourself based on the example from datetime documentation

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTC(tzinfo):

    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO


utc = UTC()

# print the current time in UTC
print(datetime.now(utc).strftime("%a %b %d %H:%M:%S %Z %Y"))
# -> Mon Oct 13 01:27:53 UTC 2014
从3.2开始,

timezone类包含在Python中:

from datetime import timezone 
print(datetime.now(timezone.utc).strftime("%a %b %d %H:%M:%S %Z %Y"))
# -> Mon Oct 13 01:27:53 UTC+00:00 2014
相关问题