Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 782
Josh Avatar asked Feb 23 '10 09:02

Josh


People also ask

How do I convert string to datetime in Python?

Method 1: Program to convert string to DateTime using datetime. strptime() function. strptime() is available in DateTime and time modules and is used for Date-Time Conversion. This function changes the given string of datetime into the desired format.

How do you change the date format of a string in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.


1 Answers

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) 
like image 69
sth Avatar answered Oct 02 '22 16:10

sth