Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date with format dd.mm.yy to yyyy-mm-dd in python

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 ?

like image 852
blues Avatar asked May 22 '15 15:05

blues


People also ask

How do I print a date in DD MMM YYYY format in Python?

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.

How do you convert date format from Yyyymmdd to dd-mm-yyyy in Python?

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.


1 Answers

Use %y instead of %Y:

>>> d2 = datetime.datetime.strptime(d1,'%d.%m.%y').strftime('%Y-%m-%d')
>>> d2
'2015-05-22'
like image 159
Simeon Visser Avatar answered Oct 09 '22 01:10

Simeon Visser