I am trying to write a function in Python 2.7 that converts a series of numbers into a valid date. So far, it all works apart form the conversion.
Here is the relevant code:
import datetime
def convert_date(x,y,z):
orig_date = datetime.datetime(x,y,z)
d = datetime.datetime.strptime(str(orig_date), '%Y-%m-%d %H:%M:%S')
result = d.strftime('%m-%d-%Y')
return orig_date
a = convert_date(13,11,12)
print a
Whenever I run this, I get:
> Traceback (most recent call last):
> File "test.py", line 9, in <module>
> a = convert_date(13,11,12)
> File "test.py", line 5, in convert_date
> d = datetime.datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')
> TypeError: must be string, not datetime.datetime
I know that this is because strptime
gives me a datetime object
, but how do I get this to work?
The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.
The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
The strftime() method returns a string representing date and time using date, time or datetime object.
For anyone who runs into this problem in the future I figured I might as well explain how I got this working.
Here is my code:
from datetime import datetime
def convert_date(x,y,z):
orig_date = datetime(x,y,z)
orig_date = str(orig_date)
d = datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')
d = d.strftime('%m/%d/%y')
return d
As I should have figured out from the error message before I posted, I just needed to convert orig_date
to a string
before using strftime
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With