Pepster K.
Pepster K.

Reputation: 349

Print current UTC datetime with special format

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

Upvotes: 7

Views: 25864

Answers (3)

jfs
jfs

Reputation: 414129

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

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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'

Upvotes: 18

behzad.nouri
behzad.nouri

Reputation: 77951

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'

Upvotes: 3

Related Questions