Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Time as %d-%m-%y

Tags:

python

am trying to print orig_time as 6/9/2013 and running into following error..can anyone provide inputs on what is wrong here

Code:

orig_time="2013-06-09 00:00:00"
Time=(orig_time.strftime('%m-%d-%Y'))
print Time

Error:-

Traceback (most recent call last):
  File "date.py", line 2, in <module>
    Time=(orig_time.strftime('%m-%d-%Y'))
AttributeError: 'str' object has no attribute 'strftime'
like image 497
user2341103 Avatar asked Sep 20 '25 11:09

user2341103


1 Answers

You cannot use strftime on a string as it is not a method of string, one way to do this is by using the datetime module:

>>> from datetime import datetime
>>> orig_time="2013-06-09 00:00:00"
#d is a datetime object    
>>> d = datetime.strptime(orig_time, '%Y-%m-%d %H:%M:%S')

Now you can use either string formatting:

>>> "{}/{}/{}".format(d.month,d.day,d.year)
'6/9/2013'

or datetime.datetime.strftime:

>>> d.strftime('%m-%d-%Y')
'06-09-2013'
like image 194
Ashwini Chaudhary Avatar answered Sep 22 '25 23:09

Ashwini Chaudhary