Wrap-up

Working with Dates and Times in Python

Max Shron

Data Scientist and Author

Recap: Dates and Calendars

  • The date() class takes a year, month, and day as arguments
  • A date object has accessors like .year, and also methods like .weekday()
  • date objects can be compared like numbers, using min(), max(), and sort()
  • You can subtract one date from another to get a timedelta
  • To turn date objects into strings, use the .isoformat() or .strftime() methods
Working with Dates and Times in Python

Recap: Combining Dates and Times

  • The datetime() class takes all the arguments of date(), plus an hour, minute, second, and microsecond
  • All of the additional arguments are optional; otherwise, they're set to zero by default
  • You can replace any value in a datetime with the .replace() method
  • Convert a timedelta into an integer with its .total_seconds() method
  • Turn strings into dates with .strptime() and dates into strings with .strftime()
Working with Dates and Times in Python

Recap: Timezones and Daylight Saving

  • A datetime is "timezone aware" when it has its tzinfo set. Otherwise it is "timezone naive"
  • Setting a timezone tells a datetime how to align itself to UTC, the universal time standard
  • Use the .replace() method to change the timezone of a datetime, leaving the date and time the same
  • Use the .astimezone() method to shift the date and time to match the new timezone
  • dateutil.tz provides a comprehensive, updated timezone database
Working with Dates and Times in Python

Recap: Easy and Powerful Timestamps in Pandas

  • When reading a csv, set the parse_dates argument to be the list of columns which should be parsed as datetimes
  • If setting parse_dates doesn't work, use the pd.to_datetime() function
  • Grouping rows with .groupby() lets you calculate aggregates per group. For example, .first(), .min() or .mean()
  • .resample() groups rows on the basis of a datetime column, by year, month, day, and so on
  • Use .tz_localize() to set a timezone, keeping the date and time the same
  • Use .tz_convert() to change the date and time to match a new timezone
Working with Dates and Times in Python

Congratulations!

Working with Dates and Times in Python

Preparing Video For Download...