Friday 15 July 2011

python - Formatting Time as %d-%m-%y -


Trying to print orig_time as 6/9/2013 and running in the following error. What is wrong?

Code:

  orig_time = "2013-06-09 00:00:00" time = (orig_time.strftime ('% m-% D-% Y ')) Print time   

Error: -

  Traceback (most recent call final): File "date.py" In line 2, the & lt; Module & gt; Time = (orig_time.strftime ('% m-% d-% Y')) attribute: error: 'str' object has no attribute 'strftime'    

You can not use strftime on a string because it is not a method of string, there is a way to do this Using the module:

  & gt; & Gt; & Gt; That time import from datetime & gt; & Gt; & Gt; Orig_time = "2013-06-09 00:00:00" #d is a datetime object & gt; & Gt; & Gt; D = datetime.strptime (orig_time, '% y-% m-% d% H:% M:% S')   

You can now use string formatting:

  & gt; & Gt; & Gt; "{} / {} / {}". Format (d.month, d.day, d.year) '6/9/2013'   

or: <> & gt; & Gt; & Gt; D.strftime ('% m-% d-% Y') '06 -0 9-2013 '

No comments:

Post a Comment