Sling Academy
Home/Python/Python: Get the day of the week based on a timestamp/datetime object

Python: Get the day of the week based on a timestamp/datetime object

Last updated: February 13, 2024

Overview

In this guide, we’ll dive into how to retrieve the day of the week from a given timestamp or datetime object in Python. Understanding and manipulating dates and times are essential for a vast array of applications, from scheduling and time tracking to historical data analysis. We will explore several methods, each suited for different needs and scenarios.

Introduction to datetime Module

The datetime module in Python provides classes for manipulating dates and times. Before we can extract the day of the week from a datetime object, let’s first see how to create a datetime object.

Remember, Python’s week starts on Monday, which is represented by 0, and ends on Sunday, represented by 6.

import datetime

# Current datetime
current = datetime.datetime.now()
print(f'Current date and time: {current}')

Now that we have a current datetime, let’s move on to getting the day of the week.

Method 1: Using the weekday() Method

The weekday() method of a datetime object returns an integer corresponding to the day of the week, where Monday is 0 and Sunday is 6.

today = datetime.datetime.now()
day_of_week = today.weekday()
print(f'Today is {"Monday" if day_of_week == 0 else "Tuesday" if day_of_week == 1 else "Wednesday" if day_of_week == 2 else "Thursday" if day_of_week == 3 else "Friday" if day_of_week == 4 else "Saturday" if day_of_week == 5 else "Sunday"}')

Method 2: The strftime() Method

This method converts a datetime object into a string according to the specified format. To get the day of the week, you can use the %A directive, which returns the full weekday name, and %a for the abbreviated name.

today = datetime.datetime.now()
print(today.strftime('%A'))  # Shows full weekday name
print(today.strftime('%a'))  # Shows abbreviated weekday name

Using calendar Module

Python’s calendar module provides useful functionalities related to calendar operations, including getting the day of the week.

import calendar
import datetime

today = datetime.datetime.now()
day_of_week = calendar.day_name[today.weekday()]
print(f'Today is: {day_of_week}')

This method returns the full name of the day of the week, making it highly readable and user-friendly.

Handling Timestamps

If you have a timestamp (number of seconds since the epoch), converting it to a `datetime` object before extracting the day is straightforward with the datetime.fromtimestamp() method.

import datetime

timestamp = 1609459200  # Example Unix timestamp for 2021-01-01

date_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
day_of_week = date_from_timestamp.weekday()
print(f'The day of the week for the given timestamp: {"Monday" if day_of_week == 0 else "Tuesday" if day_of_week == 1 else "Wednesday" if day_of_week == 2 else "Thursday" if day_of_week == 3 else "Friday" if day_of_week == 4 else "Saturday" if day_of_week == 5 else "Sunday"}')

Conclusion

In this tutorial, we covered how to get the day of the week from a timestamp or datetime object in Python using various methods. Whether you prefer working directly with datetime objects, using the calendar module for more readability, or handling timestamps, Python provides versatile tools to work with dates and times efficiently.

As you delve into more complicated projects, these skills will prove invaluable for filtering data, generating reports, and much more. If you run into any issues or have questions regarding datetime manipulation in Python, the extensive documentation and active community forums are fantastic resources.

Next Article: Python: Convert UTC Time to Local Time and Vice Versa

Previous Article: Grouping Dates by Year and Month in Python: A Comprehensive Tutorial

Series: Date and Time in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types