TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Beginner’s Guide to Datetime Format in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python AdvancedPython Tutorials

Beginner’s Guide to Datetime Format in Python

Last updated: Apr 14, 2024 9:24 pm
By Meenakshi Agarwal
Share
8 Min Read
DateTime format in Python with Examples
SHARE

In this tutorial, we’ll cover the concept of datetime format in Python and explain using examples. The datatime is a built-in module in Python, which also provides a class with the same name. We’ll explain the usage of the datetime class. So, you will learn about the date-time formatting from different points of view. Like, how to get the date time in Python and represent it in a human-readable format.

Contents
DateTime Format Using Python strftimeUsing strftime to Format DateUsing strftime to Format TimeMixed DateTime Format in PythonLocalize Date-time Using pytz ModuleParse Datetime StringsTime Difference Between the DatesHandle Time Zones with timedeltaCommon Date and Time FormatsSummary – DateTime Format in Python

In Python, the datetime format is not just getting and displaying the date and time. It also reflects the ability to set up and show different time zones. The other things are like showing a date-time string in the local native style. You can do basic operations like finding the difference between two dates, parsing a date string, etc.

How to Format DateTime in Python With Examples

As stated earlier, the Python datetime module comes with a class with the same name. It provides simple methods that we can use to represent and process date-time. The below code is one of the simplest examples.

from datetime import datetime

# Get the current date and time
current_datetime = datetime.now()
print("Current Datetime:", current_datetime)

Also Read: Python Datetime Explained with Examples

The strftime is a simple function of the datetime class. Let’s learn how to use it to format a date string.

DateTime Format Using Python strftime

The strftime method is the key to formatting datetime objects into human-readable strings. It stands for “string format time” and takes a format string as an argument.

# Example 1: Basic strftime formatting
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Datetime:", formatted_datetime)

Output:

Formatted Datetime: 2023-12-24 15:30:45

In the format string:

  • %Y represents the year with a century as a decimal number.
  • %m represents the month as a zero-padded decimal number.
  • %d represents the day of the month as a zero-padded decimal number.
  • %H represents the hour (00 to 23).
  • %M represents the minute (00 to 59).
  • %S represents the second (00 to 59).

Using strftime to Format Date

When you only need to display the date without the time, you can customize the format accordingly.

# Example 2: Custom date formatting
custom_date_format = current_datetime.strftime("%A, %B %d, %Y")
print("Custom Date Format:", custom_date_format)

Output:

Custom Date Format: Saturday, December 24, 2023

In the format string:

  • %A represents the full weekday name.
  • %B represents the full month’s name.

Check Out: Python Time Functions Explained

Using strftime to Format Time

Similarly, we can target the time component and customize the format accordingly.

# Example 3: Custom time formatting
custom_time_format = current_datetime.strftime("%I:%M %p")
print("Custom Time Format:", custom_time_format)

Output:

Custom Time Format: 03:30 PM

In the format string:

  • %I represents the hour (12-hour clock).
  • %M represents the minute.
  • %p represents either AM or PM.

Mixed DateTime Format in Python

For combined date and time formatting, merge the elements from the previous examples.

# Example 4: Custom date and time formatting
custom_datetime_format = current_datetime.strftime("%A, %B %d, %Y %I:%M %p")
print("Custom Datetime Format:", custom_datetime_format)

Output:

Custom Datetime Format: Saturday, December 24, 2023 03:30 PM

Localize Date-time Using pytz Module

To localize the datetime format, we can use Python’s PYTZ library. It lets us play with time zones in a date-time string.

Installing pytz

Before using pytz, you need to install it:

pip install pytz

Python Example to Apply Timezone

from datetime import datetime
import pytz

# Create a datetime object with timezone information
dt_with_timezone = datetime.now(pytz.timezone('America/New_York'))
print("Datetime with Timezone:", dt_with_timezone)

# Format the datetime with timezone
formatted_dt_timezone = dt_with_timezone.strftime("%Y-%m-%d %H:%M:%S %Z")
print("Formatted Datetime with Timezone:", formatted_dt_timezone)

Output:

Datetime with Timezone: 2023-12-24 15:30:45.678901-05:00
Formatted Datetime with Timezone: 2023-12-24 15:30:45 EST

In the format string:

  • %Z represents the timezone name.

Parse Datetime Strings

At times we need to parse a date string. To achieve this, we need to convert the date string into datetime. Let’s quickly use the method strptime for this purpose.

from datetime import datetime

# Example 5: Parsing datetime string
date_string = "2023-12-24 15:30:45"
parsed_datetime = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed Datetime:", parsed_datetime)

Output:

Parsed Datetime: 2023-12-24 15:30:45

The format string in strptime should match the structure of the input string.

Time Difference Between the Dates

The first thing is to convert the dates using datetime. After that, we can measure the time difference between these objects. It is useful in various applications, such as measuring elapsed time or scheduling tasks.

from datetime import datetime, timedelta

# Example 6: Time difference between datetimes
start_time = datetime(2023, 12, 24, 10, 30, 0)
end_time = datetime(2023, 12, 24, 15, 45, 30)
time_difference = end_time - start_time
print("Time Difference:", time_difference)

Output:

Time Difference: 5:15:30

The result is a time delta object representing the difference between two datetime objects. You can format the same to make it human-readable.

# Example 7: Formatting time difference
formatted_time_difference = str(time_difference)
print("Formatted Time Difference:", formatted_time_difference)

Output:

Formatted Time Difference: 5:15:30

Handle Time Zones with timedelta

When working with time differences, especially across time zones, consider using the pytz library for accurate calculations.

from datetime import datetime, timedelta
import pytz

# Example 8: Handling time zones in timedelta
start_time_utc = datetime(2023, 12, 24, 10, 30, 0, tzinfo=pytz.utc)
end_time_utc = datetime(2023, 12, 24, 15, 45, 30, tzinfo=pytz.utc)
time_difference_utc = end_time_utc - start_time_utc
print("Time Difference (UTC):", time_difference_utc)

Output:

Time Difference (UTC): 5:15:30

Common Date and Time Formats

Understanding common date and time formats becomes necessary when working with data interchange or database storage.

The ISO 8601 Format

ISO 8601 is an international standard for representing dates and times.

# Example 9: Formatting in ISO 8601 format
iso_format = current_datetime.isoformat()
print("ISO 8601 Format:", iso_format)

Output:

ISO 8601 Format: 2023-12-24T15:30:45.678901

The RFC 3339 Format

RFC 3339 is another format commonly used for date and time representation.

# Example 10: Formatting in RFC 3339 format
rfc3339_format = current_datetime.strftime("%Y-%m-%dT%H:%M:%S%z")
print("RFC 3339 Format:", rfc3339_format)

Output:

RFC 3339 Format: 2023-12-24T15:30:45+0000

Summary – DateTime Format in Python

In this comprehensive guide, you explored the datetime format in Python from various aspects. You learned strftime and used it to format date and time, localize, and parse datetime strings. You also learned to deal with time differences and understand common date and time formats.

The tutorial also mentioned how to handle time zones which is useful when you work with applications in multiple regions. Utilize the pytz library for accurate timezone support, and always handle errors gracefully when parsing datetime strings. This ability to work with dates and times effectively is a valuable skill for any Python developer. We hope this guide gave you all the tools to manage date-time effectively in Python.

Happy Coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Strings to Integers - Check Out Practical Examples How to Convert a Python String to an Integer
Next Article 10 Python Beginner Projects with Full Code 10 Python Beginner Projects for Ultimate Practice

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x