I have a date with format:
d1 = "22.05.15"
I want to change to date with format:
d1 = "2015-05-22"
I tried converting using datetime:
d2 = datetime.strptime(d1,'%d.%m.%Y').strftime('%Y-%d-%m')
But, it does not work because datetime does not support date with format '22.05.15' but only '22.05.2015'
Is there any way out to convert date of such format ?
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.
We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime. Parameter: input is the string datetime.
Use %y
instead of %Y
:
>>> d2 = datetime.datetime.strptime(d1,'%d.%m.%y').strftime('%Y-%m-%d')
>>> d2
'2015-05-22'
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