2014-10-04 95 views
2

非常简单,但我是一个python新手。我想打印当前UTC日期和时间与特殊格式:用特殊格式打印当前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 
+0

'时间'模块不是必需的。只需使用'datetime.datetime.utcnow()。strftime(“%a%b%d%H:%M:%S%Z%Y”)'可以解决你的问题了。 – stanleyxu2005 2014-10-04 13:04:31

回答

9

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' 
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' 
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 

timezone类自3.2开始包含在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