Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 958
Pepster K. Avatar asked Oct 04 '14 12:10

Pepster K.


People also ask

How do I print a UTC date?

Simply use datetime. datetime. utcnow(). strftime("%a %b %d %H:%M:%S %Z %Y") can solve your problem already.

Does datetime now return UTC time?

The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format. UTC is a universal format to represent date and time as an alternative to local time. Also known as the GMT+00 timezone.


2 Answers

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'
like image 35
behzad.nouri Avatar answered Oct 04 '22 03:10

behzad.nouri


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'
like image 97
Martijn Pieters Avatar answered Oct 04 '22 04:10

Martijn Pieters