WRITELOOP

CREATE DATETIMES ON A PYTHONIC WAY

2018 August 6

python - create datetimes on a pythonic way

Example 1:

from datetime import datetime
now = datetime.today()
start_datetime = now.replace(hour=0, minute=0)
end_datetime = now.replace(hour=23, minute=59)

Example 2:

On the example below, we wanted to store on 2 variables a start and a end date. Given an end date, we wanted to store on a variable the first day of the month.

today = datetime.today()
end_date: today - timedelta(days=1)
# VERBOSE WAY
start_date: '{year}/{month}/01'.format(
year=end_date.year,
month=end_date.month
)
start_date: datetime.strptime(start_date, '%Y/%m/%d')
# SHORTER, PYTHONIC WAY
start_date: end_date.replace(day=1)

Doing that the pythonic way required less code and less cognitive overhead. =D