Date and times with Python

From Computer Science Wiki
Revision as of 08:35, 28 March 2023 by Mr. MacKenty (talk | contribs) (Created page with "<syntaxhighlight lang="python"> import datetime # to get the current date and time: print(datetime.datetime.now()) # to get the current date: print(datetime.date.today()) # to get the current time: print(datetime.datetime.now().time()) # to get the current year: print(datetime.datetime.now().year) # to get the day of the week: print(datetime.datetime.now().weekday()) # to print the day of the week: print(datetime.datetime.now().strftime("%A")) # to ask the user to...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
import datetime

# to get the current date and time:
print(datetime.datetime.now())

# to get the current date:
print(datetime.date.today())

# to get the current time:
print(datetime.datetime.now().time())

# to get the current year:
print(datetime.datetime.now().year)

# to get the day of the week:
print(datetime.datetime.now().weekday())

# to print the day of the week:
print(datetime.datetime.now().strftime("%A"))

# to ask the user to input a date
# and convert it to a datetime object:
date = input("Enter a date (YYYY-MM-DD): ")
date = datetime.datetime.strptime(date, "%Y-%m-%d")
print(date)

# to compare two dates:
date1 = datetime.datetime.strptime("2019-01-01", "%Y-%m-%d")
date2 = datetime.datetime.strptime("2019-01-02", "%Y-%m-%d")
if date1 > date2:
    print("date1 is greater than date2")
elif date1 < date2:
    print("date1 is less than date2")
else:
    print("date1 is equal to date2")

# to see how many days are between two dates:
date1 = datetime.datetime.strptime("2019-01-01", "%Y-%m-%d")
date2 = datetime.datetime.strptime("2018-01-02", "%Y-%m-%d")
difference = date1 - date2
print(difference.days)

# to add a number of days to a date:
date1 = datetime.datetime.strptime("2019-01-01", "%Y-%m-%d")
date2 = date1 + datetime.timedelta(days=5)
print(date2)