Skip to content

bobby_dreamer

Python playing with dates

python, pandas1 min read

I have a problem, which is trying to get a next available date from within list of dates. This list of dates contains dates which are not saturday/sunday or any public holiday. My inputs will be like, what was the first available date in last 180 days, plan is to build a function like below,

Breaking down the problem

  1. Get next available from any list of dates
  2. Create function from point(1) solution to solve problem

1. Get next available from any list of dates

Initializations

Remove a week from feb between 09/02/2020 - 15/02/2020

After removing a week data looks like this

Converts string to datetime format

Main logic to get the next available date

Output:

2. Create function from point(1) solution to solve problem

Difference between .today() & .now()

.today()
Returns the current local datetime, without tzinfo

.now()
Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision

Making .now() timezone aware you will have to use import pytz

pytz.all_timezones will list all available timezones

Above timezone thing, has nothing to do with this article, i just got bit side-tracked.

Below, i am subracting 180 days from current date, that will be the base date or start date.

Now, merging point(1) and timedelta of point(2) to create a new function,

Below is the call,

Below is the logic used to generate the dates for initialization,

Other concepts used

1. map

map(func, *iterables)

  • Where func is the function on which each element in iterables (as many as they are) would be applied on.

Example 1

Example 2

Example 3 ( using repeat to have same value repeated for round() )

2. filter

filter(func, iterable)

  • Filter passes each element in the iterable through func and returns only the ones that evaluate to true.

Example 1

Example 2

Thanks