how to convert date from format 1 may 2023 to 1-5-2023 in python

You can use the datetime library in Python to convert the date from one format to another. Here's an example code snippet:

main.py
from datetime import datetime

date_str = '1 may 2023'
date_obj = datetime.strptime(date_str, '%d %B %Y')
new_date_str = date_obj.strftime('%-d-%-m-%Y')
print(new_date_str)
173 chars
7 lines

Output:

main.py
1-5-2023
9 chars
2 lines

Explanation:

  • The strptime method is used to parse the original date string into a datetime object.
  • %d represents the day of the month (without zero padding).
  • %B represents the full month name (e.g. 'May').
  • %Y represents the year.
  • The strftime method is used to format the datetime object into a new date string.
  • %-d and %-m represent the day and month without zero padding.

Note that the - symbol is used to remove the zero padding in the day and month fields. This syntax works on Unix systems, but if you're running the code on a Windows system you will need to use a different format code (such as #d and #m).

related categories

gistlibby LogSnag