© 2004-20

String to Date

Often it's useful to process a user input of a date and examine various parts or do some calculations with it
This code will show you how

# Author: A Knifton
# Date:
# Purpose: Convert a date input by the user from string  to date

from datetime import datetime

strDate = input("Enter a date (dd/mm/yyyy):")
# setup a format string to validate the input against:
strFormat = '%d/%m/%Y' #numeric in the format dd/mm/yyyy

objDate = datetime.strptime(strDate,strFormat)   #convert using the specified date format

# Now retrieve various elements from the date object
print(f"The date you entered was:\nYear:{objDate.year}, Month:{objDate.month}, Day:{}")

# get the current date/time
objNow =

# arithmetic using the two dates
objDateDiff = objNow - objDate
print(f"Current Date {objNow},\nDate you entered {objDate}, \nDifference in days {objDateDiff}")

print(f"Long format : {objDate.strftime('%A, %d %B %Y')}")