Puzzle 20 It’s a Date!

Pandas Brain Teasers — by Miki Tebeka (28 / 34)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Holding out for a Hero | TOC | What’s the Points? 👉

date_range.py

​ ​import​ ​pandas​ ​as​ ​pd​

​ start = pd.Timestamp.fromtimestamp(0).strftime(​'​​%​​Y-​​%​​m-​​%​​d'​)
​ times = pd.date_range(start=start, freq=​'M'​, periods=2)
​ ​print​(times)

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print:

​ DatetimeIndex(['1970-01-31', '1970-02-28'], dtype='datetime64[ns]', freq='M')
images/hline.png

There are two things that are puzzling here:

  • M is a month frequency.
  • First date is January 31 and not January 1.

Let’s start with M being a month frequency. You’ve probably used the infamous strftime or its cousin strptime to convert datetime to or from strings. There, M stands for minute:

​ In [1]: t = pd.Timestamp(2020, 5, 10, 14, 21, 30)
​ In [2]: t.strftime(​'​​%​​H:​​%​​M'​)
​ Out[2]: ​'14:21'​

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.