Print current UTC datetime with special format

≯℡__Kan透↙ 提交于 2020-01-03 17:09:09

问题


Pretty simple, but I'm a python newbie. I'm trying to print the current UTC date AND time with special format:

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

回答1:


time.strftime() only takes time.struct_time-like time tuples, not datetime objects.

Use the datetime.strftime() method instead:

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

but note that in Python 2.6 no timezone objects are included so nothing is printed for the %Z; the object returned by datetime.datetime.utcnow() is naive (has no timezone object associated with it).

Since you are using utcnow(), just include the timezone manually:

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



回答2:


utcnow() returns an object; you should call .strftime on that object:

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

or, pass the object as the first argument of 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'



回答3:


To print the current time in UTC without changing the format string, you could 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 class is included in Python since 3.2:

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


来源:https://stackoverflow.com/questions/26193065/print-current-utc-datetime-with-special-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!