23
loading...
This website collects cookies to deliver better user experience
This is Day 16 of the #100DaysOfPython challenge.
hello-python-datetimes
directory and install the required dependencies.# Make the `hello-python-datetimes` directory
$ mkdir hello-python-datetimes
$ cd hello-python-datetimes
# Init the virtual environment
$ pipenv --three
$ pipenv install --dev ipython
# Create a folder to place files
$ mkdir src
# Create the required files
$ touch src/datetimes.py
datetime
library.pipenv shell ipython
. This will activate the virtual shell and start an iPython interactive shell.from datetime import date
and play around with it:from datetime import date
date(2021, 8, 4).isocalendar()
# datetime.IsoCalendarDate(year=2021, week=31, weekday=3)
date(2021, 8, 4).isoformat()
# '2021-08-04'
date(2021, 8, 4).ctime()
# 'Wed Aug 4 00:00:00 2021'
date(2021, 8, 4).strftime('%A')
# Wednesday
today = date.today()
# datetime.date(2021, 8, 4)
date
class. More information about the date
class can be found here.YYYY-MM-DD
is before today. Exit the iPython kernel and add the following code to our src/datetimes.py
file:from datetime import date
def is_date_before_today(date_str: str):
"""Check if date is before today
Args:
date_str (str): String of a date to pass
Returns:
bool: Value of if date is before today
"""
try:
date_obj = date.fromisoformat(date_str)
return date_obj < date.today()
except Exception:
return False
print(is_date_before_today("2019-01-01"))
print(is_date_before_today("2022-01-01"))
print(is_date_before_today("2021-08-03"))
print(is_date_before_today("2021-08-04"))
>
and <
operators to compare dates.python src/datetimes.py
we should see the following output:$ python src/datetimes.py
True # "2019-01-01"
False # "2022-01-01"
True # "2021-08-03"
False # "2021-08-04"
False
).datetime
module from the datetime
library also has a now
method that returns the current date and time.strftime
to get the current date and time in a string format. Update the code to the following:from datetime import date, datetime
def is_date_before_today(date_str: str):
"""Check if date is before today
Args:
date_str (str): String of a date to pass
Returns:
bool: Value of if date is before today
"""
try:
date_obj = date.fromisoformat(date_str)
return date_obj < date.today()
except Exception:
return False
now = datetime.now()
now_str = now.strftime('%Y-%m-%d')
print(now_str)
print(is_date_before_today(now_str))
python src/datetimes.py
will output 2021-08-04
and False
respectively.To learn more about strftime
, there is a great blog post here.
datetime.timedelta
to add and subtract dates.from datetime import date, datetime, timedelta
def is_date_before_today(date_str: str):
"""Check if date is before today
Args:
date_str (str): String of a date to pass
Returns:
bool: Value of if date is before today
"""
try:
date_obj = date.fromisoformat(date_str)
return date_obj < date.today()
except Exception:
return False
now = datetime.now()
now_str = now.strftime('%Y-%m-%d')
print(now_str)
print(is_date_before_today(now_str))
now_subtract_one_day = now - timedelta(days=2)
now_subtract_one_day_str = now_subtract_one_day.strftime('%Y-%m-%d')
print(now_subtract_one_day_str)
print(is_date_before_today(now_subtract_one_day_str))
now_add_one_day = now + timedelta(days=1)
now_add_one_day_str = now_add_one_day.strftime('%Y-%m-%d')
print(now_add_one_day_str)
print(is_date_before_today(now_add_one_day_str))
python src/datetimes.py
which will output the following:$ python src/datetimes.py
2021-08-04
False
2021-08-02
True
2021-08-05
False
datetime
module to compare times and determine the current date.pawel_czerwinski