user2341103
user2341103

Reputation: 2433

Formatting Time as %d-%m-%y

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'

Upvotes: 4

Views: 63907

Answers (4)

tk20blue
tk20blue

Reputation: 45

import time

now1 = time.strftime("%d-%m-%y", time.localtime())
print(now1)

If you'd prefer, you can change the "d-m-y" as you want and can use a static time.

Upvotes: 0

Tomy Ariswara
Tomy Ariswara

Reputation: 11

import time

orig_time="2013-06-09 00:00:00" 

Time= time.strftime(orig_time, '%m-%d-%Y')

print Time

Upvotes: -1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

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'

Upvotes: 12

Joran Beasley
Joran Beasley

Reputation: 113988

>>> import time
>>> time.strftime("%m-%d-%y",time.strptime("2013-06-09 00:00:00","%Y-%m-%d %H:%M:%S"))
'06-09-13'

but its more of a pain to remove leading zeros ... If you need that use the other answer

also its unclear what you want, since your title says one thing (and your format string), but it does not match what you say is your expected output in the question

Upvotes: 1

Related Questions