Converting a string to a formatted date-time string using Python Converting a string to a formatted date-time string using Python python python

Converting a string to a formatted date-time string using Python


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)


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)

gives05:09 29 December 2009 (UTC)


from datetime import datetimes = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")print("{:%H:%M %d %B %Y (UTC)}".format(s))