Home > Back-end >  how can i convert yyyy-MM-dd (date.today()) to ddMMyyyy(string or date) in python
how can i convert yyyy-MM-dd (date.today()) to ddMMyyyy(string or date) in python

Time:09-29

how do i convert a date: 2022-09-28 to 28092022 in python? I have some files that have this date pattern in their name and I need to convert this date to find the latest one, is possible?

Every help is welcome :)

CodePudding user response:

So, when you use date.today() you get back a datetime.date object:

>>> from datetime import date
>>> date.today()
datetime.date(2022, 9, 28)

On this, you can directly use the .strftime() method to get back a string with whatever format you would like:

>>> date.today().strftime('%d%m%Y')
'28092022'

CodePudding user response:

You can use this function:

def getDateString(date):
    year, month, day = str(date).split("-")
    return day month year

Eg:

date = datetime(year=2022, month=9, day = 28).date()
print(getDateString(date)) // returns '28092022'

CodePudding user response:

we can use regex to get the task done:

the first step should be to get the date expression from the file name. (if there is more than one file name to read and modify, we can run the task in a loop).

extract the date expression from the file name:

import re
file_name = 'backup 2022-09-28-17:33.xyz' # a sample file name
pattern = r'(\d{4}-\d{2}-\d{2})'
date = ''.join(re.findall(pattern, file_name)).split('-')

result of date: ['2022', '09', '28']

in the second step we replace the current date expression by the new ones:

file_name = re.sub(pattern, ''.join(date[::-1]), file_name)
print(file_name)

result: backup 28092022-17:33.xyz

  • Related