chapter eleven

11 Working with Dates and Times

 

This chapter covers:

  • Converting string columns to datetime columns
  • Accessing date and time information from datetime values
  • Rounding dates to week, month, and quarter ends
  • Adding and subtracting datetimes from each other

A datetime is a data type used to store date and time information. A datetime can represent a specific date (i.e., October 4th, 2021), a specific time (i.e., 11:50AM), or both (i.e., October 4th, 2021 at 11:50AM). Datetimes are one of the most valuable pieces of information available in a dataset because they hold the key to identifying trends over time. A financial analyst may use datetimes to track the weekdays that a stock performs best. A restaurant owner may use them to identify the peak hours that customers are patronizing their business. An operations manager may use datetimes to identify what parts of a process are creating bottlenecks in production. The when in a dataset can often lead to the why.

In this chapter, we'll review Python's built-in solutions for datetimes and how Pandas improves upon them with the Timestamp and Timedelta objects. We'll see how we can use the library to convert strings to dates, add and subtract offsets of time, calculate durations, and more. 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 a Column or Index to Store 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    Questions

11.8.2    Answers

11.9  Summary