How to Convert YYYY-MM to Date in Python?

Estimated read time 1 min read

You can use the datetime module in Python to convert a string in the YYYY-MM format to a date. Here’s an example code snippet:

from datetime import datetime

date_string = '2022-05'

# Parse the date string into a datetime object
date = datetime.strptime(date_string, '%Y-%m').date()

# Print the resulting date object
print(date)

In this example, we start with a string in the YYYY-MM format (date_string). We use the strptime() method of the datetime module to parse the string into a datetime object, and then we extract the date component of the datetime object using the date() method. Finally, we print the resulting date object.

The second argument to strptime() specifies the format of the input string. In this case, %Y corresponds to the year with century as a decimal number, and %m corresponds to the month as a zero-padded decimal number. You can find more information on the available format codes in the datetime module documentation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply