John
John

Reputation: 1

Convert a datetime object

In Python how do I convert a datetime object like datetime.datetime(2010, 12, 18, 22, 21, 45, 277000) to something like "Sun Dec 18 2010 22:21:45 GMT+0000 (UTC)"?

Upvotes: 0

Views: 126

Answers (1)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

You can use strftime for this purpose. Read more here.

Not sure about utc offset, but seems that you can use something like this:

import datetime
d = datetime.datetime(2010, 12, 18, 22, 21, 45, 277000)
d.strftime("%a %b %d %Y %H:%M:%S %z")
>>> Sat Dec 18 2010 22:21:45

Where using the link above:

  • %a - Locale’s abbreviated weekday name

  • %b - Locale’s abbreviated month name

  • %d - Day of the month as a decimal number [01,31]

  • %H - Hour (24-hour clock) as a decimal number [00,23]

  • %M - Minute as a decimal number [00,59]

  • %S - Second as a decimal number [00,61]

  • %z - UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive)

Upvotes: 3

Related Questions