Python Dates

About Python Dates

In Python, dates are used to work with calendar-based values like year, month, day, minutes, time, and so on. Python doesn’t have a built-in date data type, but it provides the datetime module to handle dates and times.

It is important to learn how to work with dates in Python, as they are commonly used in various applications for scheduling, logging events, and managing time-based data.

The datetime module provides classes for manipulating dates and times in both simple and complex ways. It allows you to create, format, and perform arithmetic operations on date and time objects.

Using the datetime Module

Importing and using the datetime module

To work with dates and times in Python, you first need to import the datetime module. You can do this in the following ways:

Import the entire datetime module
  • import datetime: This line imports the datetime module, which contains classes and functions for working with dates and times.
  • datetime.datetime.now(): This function retrieves the current date and time from the system. The first datetime refers to the module, and the second datetime refers to the class within that module.
  • print(currentTime): This line prints the current date and time to the console.
Import specific classes from the datetime module
  • from datetime import datetime, date: This line imports only the datetime and date classes from the datetime module, allowing you to use them directly without prefixing them with the module name.
  • datetime.now(): This function retrieves the current date and time from the system. Since we imported the datetime class directly, we can call it without the module prefix.
  • date.today(): This function retrieves the current date from the system. Similar to datetime.now(), we can call it directly because we imported the date class.

Creating Date and Time Objects

The datetime module provides several classes to represent dates and times, including datetime, date, and time. You can create instances of these classes to represent specific dates and times.

Create a specific date and time object

To create a date and time object in Python, you can use the datetime class from the datetime module. Here is an example of how to create a specific date and time object:

Create a specific date object

To create a date object in Python, you can use the date class from the datetime module. Here is an example of how to create a specific date object:

Create a specific time object

To create a time object in Python, you can use the time class from the datetime module. Here is an example of how to create a specific time object:

Creating Current Date and Time Objects

You can create a current date and time object using the now() method from the datetime class. This method retrieves the current date and time from the system clock.

You can also use the today() method to get the current date and time, and the utcnow() method to get the current date and time in Coordinated Universal Time (UTC).

Here is an example of how to create a current date and time object using the now(), today(), and utcnow() methods:

Creating timedelta Objects

The timedelta class in the datetime module is used to represent a duration, i.e., the difference between two dates or times.

You can create a timedelta object by specifying the number of days, hours, minutes, seconds, milliseconds, microseconds, and weeks.

Here is an example of how to create a timedelta object:

Performing arithmetic operations with timedelta

You can perform arithmetic operations with timedelta objects, such as addition and subtraction. Here is an example of how to add and subtract a timedelta object from a datetime object:

Find difference of two datetime objects

You can find the difference between two datetime objects by subtracting one from the other. This will give you a timedelta object that represents the duration between the two dates. Here is an example:

Formatting Dates and Times

You can format date and time objects into readable strings using the strftime() method. This method allows you to specify the format in which you want to display the date and time.

Common format codes used in strftime()
  • %Y: Year with century (e.g., 2023)
  • %y: Year without century (e.g., 23 for 2023)
  • %m: Month as a zero-padded decimal number (e.g., 12 for December)
  • %d: Day of the month as a zero-padded decimal number (e.g., 25)
  • %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 15 for 3 PM)
  • %I: Hour (12-hour clock) as a zero-padded decimal number (e.g., 03 for 3 PM)
  • %M: Minute as a zero-padded decimal number (e.g., 30)
  • %S: Second as a zero-padded decimal number (e.g., 45)
  • %A: Full weekday name (e.g., Monday)
  • %a: Abbreviated weekday name (e.g., Mon)
  • %B: Full month name (e.g., December)
  • %b: Abbreviated month name (e.g., Dec)
  • %p: AM or PM designation
  • %f: Microsecond as a decimal number, zero-padded on the left (e.g., 000000 to 999999)
  • %j: Day of the year as a zero-padded decimal number (e.g., 001 to 366)
  • %U: Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number (e.g., 00 to 53)
  • %W: Week number of the year (Monday as the first day of the week) as a zero-padded decimal number (e.g., 00 to 53)

Here are some examples of how to format a datetime object using the strftime() method:

Converting Strings to Dates Using strptime()

You can convert a string representation of a date and time into a datetime object using the strptime() method. This method allows you to specify the format of the input string so that it can be correctly parsed into a date and time object.

It is important to match the format of the input string with the format codes used in the strptime() method to ensure accurate conversion. Otherwise, you may encounter errors or incorrect date and time values.

Here is an example of how to convert a string to a datetime object using the strptime() method:

Python Compiler For Live Practice

Practice the above Python code in the following Python Editor. Try different datetime module classes and their functions and variables in the following code editor and click Execute button. Output will be displayed in Python Code Output section.

Python logo Python Editor
Python Code Output