Python Date and Time Tutorial

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

Working with dates and times is a common task in many programming scenarios. Python provides several modules to handle date and time operations, such as datetime, time, calendar, and dateutil. This tutorial covers the basics of working with dates and times in Python, including creating, formatting, and manipulating dates and times.

Table of Contents

  1. Introduction to Python Date and Time
  2. The datetime Module
  3. Creating Date and Time Objects
  4. Getting the Current Date and Time
  5. Formatting Dates and Times
  6. Parsing Dates and Times
  7. Working with Time Deltas
  8. Time Zones
  9. The time Module
  10. The calendar Module
  11. Handling Date and Time in Pandas
  12. Conclusion

1. Introduction to Python Date and Time

Python provides several modules to work with dates and times. The most commonly used module is datetime, which offers a range of classes to handle dates, times, and intervals.

2. The datetime Module

The datetime module provides classes for manipulating dates and times. The key classes are:

  • datetime.date: A class for working with dates.
  • datetime.time: A class for working with times.
  • datetime.datetime: A class for working with both dates and times.
  • datetime.timedelta: A class for representing the difference between two dates or times.

Example

import datetime # Printing the classes print(datetime.date) print(datetime.time) print(datetime.datetime) print(datetime.timedelta) 

3. Creating Date and Time Objects

You can create date and time objects using the date(), time(), and datetime() constructors.

Example

import datetime # Creating a date object date_obj = datetime.date(2023, 12, 25) print("Date:", date_obj) # Creating a time object time_obj = datetime.time(14, 30, 0) print("Time:", time_obj) # Creating a datetime object datetime_obj = datetime.datetime(2023, 12, 25, 14, 30, 0) print("Datetime:", datetime_obj) 

4. Getting the Current Date and Time

You can get the current date and time using the today(), now(), and utcnow() methods.

Example

import datetime # Getting the current date current_date = datetime.date.today() print("Current Date:", current_date) # Getting the current local date and time current_datetime = datetime.datetime.now() print("Current Datetime:", current_datetime) # Getting the current UTC date and time current_utc_datetime = datetime.datetime.utcnow() print("Current UTC Datetime:", current_utc_datetime) 

5. Formatting Dates and Times

You can format dates and times using the strftime() method. The strftime() method takes a format string and returns the formatted date or time as a string.

Example

import datetime now = datetime.datetime.now() # Formatting the current date and time formatted_datetime = now.strftime("%Y-%m-%d %H:%M:%S") print("Formatted Datetime:", formatted_datetime) # Formatting the current date formatted_date = now.strftime("%A, %d %B %Y") print("Formatted Date:", formatted_date) # Formatting the current time formatted_time = now.strftime("%I:%M %p") print("Formatted Time:", formatted_time) 

6. Parsing Dates and Times

You can parse dates and times from strings using the strptime() method.

Example

import datetime # Parsing a date and time from a string date_string = "2023-12-25 14:30:00" parsed_datetime = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") print("Parsed Datetime:", parsed_datetime) # Parsing a date from a string date_string = "25 December, 2023" parsed_date = datetime.datetime.strptime(date_string, "%d %B, %Y").date() print("Parsed Date:", parsed_date) 

7. Working with Time Deltas

The timedelta class represents the difference between two dates or times. You can perform arithmetic operations with timedelta objects.

Example

import datetime # Creating a timedelta object delta = datetime.timedelta(days=5, hours=3, minutes=30) # Getting the current date and time now = datetime.datetime.now() # Adding a timedelta to the current date and time future_datetime = now + delta print("Future Datetime:", future_datetime) # Subtracting a timedelta from the current date and time past_datetime = now - delta print("Past Datetime:", past_datetime) 

8. Time Zones

Python provides the pytz library for handling time zones. You can install it using pip install pytz.

Example

import datetime import pytz # Getting the current time in UTC utc_now = datetime.datetime.now(pytz.utc) print("Current UTC Time:", utc_now) # Converting UTC time to a specific time zone india_tz = pytz.timezone('Asia/Kolkata') india_time = utc_now.astimezone(india_tz) print("India Time:", india_time) # Creating a datetime object with a time zone tz_aware_datetime = datetime.datetime(2023, 12, 25, 14, 30, 0, tzinfo=india_tz) print("Timezone Aware Datetime:", tz_aware_datetime) 

9. The time Module

The time module provides functions for working with time, including getting the current time, sleeping, and measuring time intervals.

Example

import time # Getting the current time in seconds since the epoch current_time = time.time() print("Current Time (seconds since epoch):", current_time) # Sleeping for a specified number of seconds print("Sleeping for 2 seconds...") time.sleep(2) print("Awake now!") # Measuring time intervals start_time = time.time() # Simulating a task by sleeping for 2 seconds time.sleep(2) end_time = time.time() elapsed_time = end_time - start_time print("Elapsed Time:", elapsed_time) 

10. The calendar Module

The calendar module provides functions for working with calendars, including printing calendars and checking for leap years.

Example

import calendar # Printing the calendar for a specific year year = 2023 print(calendar.calendar(year)) # Checking if a year is a leap year print("2020 is a leap year:", calendar.isleap(2020)) print("2023 is a leap year:", calendar.isleap(2023)) # Getting the number of leap years in a range leap_years = calendar.leapdays(2000, 2020) print("Number of leap years between 2000 and 2020:", leap_years) 

11. Handling Date and Time in Pandas

The pandas library provides powerful tools for working with date and time data in dataframes. You can install it using pip install pandas.

Example

import pandas as pd # Creating a datetime series dates = pd.date_range("20230101", periods=6) print("Datetime Series:") print(dates) # Creating a dataframe with datetime index data = {"Value": [1, 2, 3, 4, 5, 6]} df = pd.DataFrame(data, index=dates) print("\nDataframe with Datetime Index:") print(df) # Converting a column to datetime df["Date"] = pd.to_datetime(["2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04", "2023-01-05", "2023-01-06"]) print("\nDataframe with Datetime Column:") print(df) # Extracting date components df["Year"] = df["Date"].dt.year df["Month"] = df["Date"].dt.month df["Day"] = df["Date"].dt.day print("\nDataframe with Extracted Date Components:") print(df) 

12. Conclusion

Working with dates and times in Python is made easy with modules like datetime, time, calendar, and libraries like pytz and pandas. By understanding how to create, format, and manipulate date and time objects, you can effectively handle temporal data in your Python applications. This tutorial covered the basics of working with dates and times, including creating date and time objects, getting the current date and time, formatting and parsing dates and times, working with time deltas, handling time zones, and using the time and calendar modules. Additionally, we explored handling date and time data in pandas for more advanced data manipulation.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare