Kodeclik Blog


Pandas date_range()

Pandas date_range() is a function used to generate date ranges from start and end dates. This can be useful when analyzing datasets that contain temporal data such as stock prices over time, or social media clicks by day, or a company’s sales figures over months.
Here is a very basic program to illustrate how date_range() works:
We first import pandas (“as pd”) and then call the date_range() function with a start and end dates. Finally we print the returned values (i.e., dates). The output in this case is:
Note that date_range() by default uses a daily frequency (specified in the last line of the output, as freq=’D’). We also see that this gives rise to 365 values since there are 365 days in a year. If we wish a different frequency, we can update our call giving a specific freq parameter:
The output will be:
Note that date_range() is cognizant of the fact that different months have different numbers of days. The output has 12 values, all situated at the end of the respective month. This is because ‘M’ denotes end of the month. If you would like the dates to be at the beginning of the month, use ‘MS’ as the value for frequency (for ‘month start’). Thus if we try:
we will get:
as expected.
You can try to create a date range at a biweekly interval (perhaps you are trying to simulate pay dates):
The output will be:
Note that we obtain 25 pay dates for the year 2023. A better way to do it is to use the in-built frequency called ‘SMS’ (which stands for: semi-month start frequency (1st and 15th of each month)).
Thus if we try:
we will get:
Note that this time we obtain 24 dates, not 25.
Below is an exhaustive list of the frequencies you can use:
So, to summarize, Pandas’s date_range() function allows you to quickly generate lists of dates with ease - whether they need specific start/end points or relative offsets between them! So if you're looking for an easy way to generate lists of dates - give date_range in Pandas a try!
For more about dates, checkout our blogpost on comparing dates in Python.
If you liked this blogpost, checkout our blogpost on returning a specific row or set of rows from a Pandas data frame.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.