Home > OS >  Reversing the date order of "%Y-%m-%d" to "%d-%m-%Y"
Reversing the date order of "%Y-%m-%d" to "%d-%m-%Y"

Time:09-25

Using todays date, I would like to reformat the date so that it reads as follows:

25-09-2021

So far I have come up with a very clumsy way of doing:

from datetime import datetime, timedelta, date

print(datetime.now())

the_date = datetime.strftime(datetime.now(), '%Y-%m-%d')
print(the_date)
a = the_date[-2:]
print(a)
b = the_date[5:-3]
print(b)
c = the_date[:4]
print(c)


new_date = str(a) '-' str(b) '-' str(c)

print(new_date)

Surely there is a cleaner way of doing this?

CodePudding user response:

You could simply specify the formula differently:

datetime.strftime(datetime.now(), '%d-%m-%Y')

CodePudding user response:

It is not clear what type of data you are starting with. If you have an existing date string in the format YYYY-MM-DD, you can split and reorder it.

Here's an example.

date = '2021-09-25'
Y, M, D = date.split('-')
date = f"{D}-{M}-{Y}"
print(date) # Prints 25-09-2021

CodePudding user response:

Assuming you start with a string with the given format

original_date_str = datetime.now().strftime('%Y-%m-%d')

#this line recreates a datetime object from the string
original_date_datetime = datetime.strptime(original_date_str, '%Y-%m-%d')

#this value will be a string with the new format
new_fmt_date_str = original_date_datetime.strftime("%d-%m-%Y")

I haven't tested the code yet, but pending some silly mistake it should work.

  • Related