Converting a string to a formatted date-time string using Python
Asked Answered
G

5

23

I'm trying to convert a string "20091229050936" into "05:09 29 December 2009 (UTC)"

>>>import time
>>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S")
>>>print s.strftime('%H:%M %d %B %Y (UTC)')

gives AttributeError: 'time.struct_time' object has no attribute 'strftime'

Clearly, I've made a mistake: time is wrong, it's a datetime object! It's got a date and a time component!

>>>import datetime
>>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")

gives AttributeError: 'module' object has no attribute 'strptime'

How am I meant to convert a string into a formatted date-string?

Genitourinary answered 23/2, 2010 at 9:29 Comment(0)
G
14

time.strptime returns a time_struct; time.strftime accepts a time_struct as an optional parameter:

>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
>>>print time.strftime('%H:%M %d %B %Y (UTC)', s)

gives 05:09 29 December 2009 (UTC)

Genitourinary answered 23/2, 2010 at 9:29 Comment(0)
P
43

For datetime objects, strptime is a static method of the datetime class, not a free function in the datetime module:

>>> import datetime
>>> s = datetime.datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
>>> print s.strftime('%H:%M %d %B %Y (UTC)')
05:09 29 December 2009 (UTC)
Precious answered 23/2, 2010 at 9:39 Comment(1)
Pedantic point: It's a class method, not a static method. The difference is that class methods are passed the class itself as an argument, and can therefore behave dynamically for subclasses; alternate constructors (like strptime) are always (or at least should always) be class methods.Stelu
G
14

time.strptime returns a time_struct; time.strftime accepts a time_struct as an optional parameter:

>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
>>>print time.strftime('%H:%M %d %B %Y (UTC)', s)

gives 05:09 29 December 2009 (UTC)

Genitourinary answered 23/2, 2010 at 9:29 Comment(0)
B
2

For me this is the best and it works on Google App Engine as well

Example showing UTC-4

import datetime   
UTC_OFFSET = 4
local_datetime = datetime.datetime.now()
print (local_datetime - datetime.timedelta(hours=UTC_OFFSET)).strftime("%Y-%m-%d %H:%M:%S")
Benson answered 25/7, 2011 at 1:59 Comment(0)
I
2
from datetime import datetime
s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")
print("{:%H:%M %d %B %Y (UTC)}".format(s))
Ileostomy answered 3/4, 2014 at 15:52 Comment(0)
G
1

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.string_to_string("20091229050936", "%Y%m%d%H%M%S", "%H:%M %d %B %Y (UTC)")
Gutturalize answered 10/5, 2015 at 5:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.