11 Working with dates and times

 

This chapter covers

  • Converting Series of strings to datetimes
  • Retrieving date and time information from datetime objects
  • Rounding dates to week, month, and quarter ends
  • Adding and subtracting datetimes to and from each other

A datetime is a data type for storing date and time. It can model a specific date (such as October 4, 2021), a particular time (such as 11:50 a.m.), or both (such as October 4, 2021 at 11:50 a.m.). Datetimes are valuable because they allow us to track trends over time. A financial analyst may use datetimes to determine the weekdays when a stock performs best. A restaurant owner may use them to discover the peak hours that customers are patronizing the business. An operations manager may use them to identify the parts of a process that are creating bottlenecks in production. The when in a data set can often lead to the why.

In this chapter, we’ll review Python’s built-in datetime objects and see how pandas improves them with its Timestamp and Timedelta objects. We’ll also learn how to use the library to convert strings to dates, add and subtract offsets of time, calculate durations, and more. There’s no time to waste (pun intended), so let’s dive in.

11.1 Introducing the Timestamp object

11.1.1 How Python works with datetimes

11.1.2 How pandas works with datetimes

11.2 Storing multiple timestamps in a DatetimeIndex

11.3 Converting column or index values to datetimes

11.4 Using the DatetimeProperties object

11.5 Adding and subtracting durations of time

11.6 Date offsets

11.7 The Timedelta object

11.8 Coding challenge

11.8.1 Problems

11.8.2 Solutions

Summary