Dealing with dates and times in Python can be a hassle. Thankfully, there’s a built-in way of making it easier: the Python datetime module.
datetime
helps us identify and process time-related elements like dates, hours, minutes, seconds, days of the week, months, years, etc. It offers various services like managing time zones and daylight savings time. It can work with timestamp data. It can extract the day of the week, day of the month, and other date and time formats from strings.
In this example, we will take date data from the user in string format and convert this date into a date object.
Python Code : Get date only
1 2 3 4 5 6 7 8 | from datetime import datetime my_string = str(input('Enter date(yyyy-mm-dd): ')) my_date = datetime.strptime(my_string, "%Y-%m-%d") print(my_date) |
Output:
1 2 3 4 | Enter date(yyyy-mm-dd): 2000-01-20 2000-01-20 00:00:00 |
Python Code: Get date and time
1 2 3 4 5 6 7 8 | from datetime import datetime my_string = str(input('Enter date(yyyy-mm-dd hh:mm): ')) my_date = datetime.strptime(my_string, "%Y-%m-%d %H:%M") print(my_date) |
Output:
1 2 3 4 | Enter date(yyyy-mm-dd hh:mm): 2000-01-25 14:30 2000-01-25 14:30:00 |
thank you so much