Record#
Today I learned about date handling in Python and used the datetime
module.
Time handling in computers is based on the number of seconds since January 1, 1970, known as "Unix Epoch".
In the code for handling time, we first need to import the datetime
module. Here are some commonly used operations:
-
Inserting a specific date: Use the
datetime.date()
function, for example:myDate = datetime.date(year=2022, month=12, day=7)
. It is important to note that for single-digit months, such as August, you should usemonth = 8
instead ofmonth = 08
. -
Getting today's date: Use the
datetime.date.today()
function, for example:myDate = datetime.date.today()
. -
datetime.timedelta
is a class in Python used to represent time intervals or durations. It can be used for simple arithmetic operations between dates and times, such as calculating the difference between two dates or adding or subtracting a certain amount of time from an existing date or time. -
Dates can be compared directly using comparison operators such as
+
,-
,<
,>
,<=
,>=
,!=
.
Today's exercise involves comparing and calculating with user-inputted dates.
CODE#
import datetime
print("🌟Event Countdown Timer🌟")
today = datetime.date.today()
event = input("Input the event > ")
year = int(input("Input the year > "))
month = int(input("Input the month > "))
day = int(input("Input the day > "))
eventdate = datetime.date(year, month, day)
daynum = eventdate - today
daynum = daynum.days
if eventdate > today:
print(f"{event} coming soon...{daynum}")
elif eventdate < today:
print(f"Hope you enjoyed {event}, {daynum}")
else:
print(f"{event} is today")