Gyasi Sutton, MD, MPH Physician in Training, Coder at heart. Python, R, Node, and Rust.

Mastering Time: A Beginner's Guide to Date and Time Manipulation in Python

  Reading Time:

Sooner or later, during your coding journey, you are going to come across the need to manipulate time and dates. Especially if you deal with medical records as every entry, assessment, treatment, etc, should have a time and date associated with it. Different environment and languages have their own specific quirks(I'm looking at you SAS) when it comes to handling these aspects, and in this article, we are going to talk about python's modules for handling such objects. Python has a built-in module called datetime that provides the necessary classes and functions to work with dates and times. However, there are other third-party packages like dateutil, pytz, and pendulum that can make working with dates and times even easier. We will start with the datetime module first.

The datetime module provides the datetime class, which can be used to represent a specific point in time. The datetime class takes three arguments: the year, the month, and the day. For example:

from datetime import datetime
now = datetime(2022, 12, 1)
print(now)
# Output: 2022-12-01 00:00:00

The datetime module also provides the date class, which can be used to represent a specific date without a time. The date class takes three arguments: the year, the month, and the day. For example:

from datetime import date
today = date.today()
print(today)
# Output: 2022-12-01

You can also use the datetime.now() function to get the current date and time, and the datetime.utcnow() function to get the current date and time in UTC.

The datetime module also provides the timedelta class, which can be used to represent a duration of time. The timedelta class takes several arguments, such as days, seconds, microseconds, milliseconds, minutes, hours, and weeks.

For example, to get the date and time one day from now:

from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(tomorrow)
# Output: 2022-12-02 10:15:30.283740

You can also subtract timedelta from datetime to get the date and time before.

To get rid of the time component in a datetime object, you can use the date() method, which returns a date object with the same year, month, and day as the datetime object.

For example:

from datetime import datetime
now = datetime.now()
print(now)
# Output: 2022-12-01 10:15:30.283740
date_only = now.date()
print(date_only)
# Output: 2022-12-01

To output a date in a human-readable format, you can use the strftime() method, which allows you to format the date and time using codes that represent the various components of the date and time.

For example, to output a date in the format "YYYY-MM-DD":

now = datetime.now()
print(now.strftime("%Y-%m-%d"))
# Output: 2022-12-01

But as mentioned before python's datetime module has its limitations, so developers often use third party packages like dateutil , pytz, pendulum to work with dates and times.

The dateutil package provides a parser.parse() method that can parse almost any string representation of date and time, and also includes a relativedelta() function that can be used to perform arithmetic operations with dates and times.

For example, to format a date in the format "YYYY-MM-DD" using the dateutil package:

from dateutil import parser
now = parser.parse("2022-12-01")
print(now.strftime("%Y-%m-%d"))
# Output: 2022-12-01

Another package for date and time manipulation is pytz, which provides the timezone information.

import pytz
now = datetime.now(pytz.UTC)

This will give you the date and time in UTC format.

pendulum is another package that provides simple, easy-to-use, and Pythonic methods for creating, manipulating, formatting, and parsing dates and times. It also includes timezone support and advanced features such as period arithmetic, recurrences, and humanization.

import pendulum
now = pendulum.now()
print(now.to_date_string())

This will give you the date in string format 'YYYY-MM-DD'

Datetime syntax table
Code Explanation Output (example)
%a Abbreviated weekday name Mon
%A Full weekday name Monday
%b Abbreviated month name Dec
%B Full month name December
%d Day of the month (zero-padded) 01
%m Month of the year (zero-padded) 12
%Y Year with century 2022
%H Hour (24-hour format) 00
%I Hour (12-hour format) 12
%M Minute 30
%S Second 45

In conclusion, python's datetime module provides the necessary classes and functions to work with dates and times, but third-party packages like dateutil, pytz, and pendulum can make working with dates and times even easier. These packages provide additional features such as parsing and formatting dates, timezone support, and advanced features such as period arithmetic, recurrences, and humanization. It is recommended to choose the package that best fits your requirements and use the appropriate methods to format your date and time.

Of course, this is just the tip of the iceberg. For a deeper dive check out these links to libraries:

-- Stay tuned for Part 2 of this time series for R

Crafting Effective Prompts for AI-Generated Text

Prompt engineering is a critical aspect of natural language processing (NLP) and is central to the development of language models. By carefully designing prompts, we can...

Demystifying User Permissions and Access in Linux for Developers

In Linux, permissions and access control are fundamental concepts that govern the security of a system. The users of a Linux system can have different levels...