How to convert a Python string to a date?

In Python, you can use the datetime module to convert a string to a date. One common method to do this is as follows:

from datetime import datetime

date_str = "2021-10-15"  # 你的日期字符串
date_format = "%Y-%m-%d"  # 日期的格式

date = datetime.strptime(date_str, date_format)
print(date)

In the above code, the strptime() function is used to convert a string into a date object based on the specified format. In this example, we are using %Y-%m-%d as the format, which represents the year-month-date format.

Please note that the strptime() function returns a datetime object, which can be further manipulated or formatted as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds