PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Python DateTime » Python DateTime Format Using Strftime()

Python DateTime Format Using Strftime()

Updated on: May 6, 2022 | 4 Comments

This tutorial will teach how to represent date and time into various formats in Python using the strftime() function of a datetime module and time module.

The strftime() method returns a string representing of a datetime object according to the format codes.

Table of contents

  • How to Format Date and Time in Python
    • Example: Convert DateTime to String Format
  • strftime() Date Format Codes
    • Represent Dates in Numerical Format
    • Represent Dates in Textual Format
  • Convert Only Date to String
  • Convert Time Object to String Format
    • Represent time in 24-hours and 12-hours Format
    • Represent Time in Microseconds Format
    • Represent DateTime in Milliseconds
    • Represent Time in AM/PM Format
    • Format time Object to String Using time module
  • Convert Datetime to locale’s Format
  • Convert Datetime in ISO String format
  • Converting Datetime to Int
  • Convert Datetime to Float

How to Format Date and Time in Python

In Python, the date and time values are stored as datetime objects, but there are cases where we need to print the datetime objects into various string formats for better readability.

For example, you may need to represent a date numerically in format, like “17-06-2021“. On the other hand, you want to convert dates in textual string format like “Tuesday, 23 June 2021.”

The below steps show how to convert a datetime to string format using the strftime() function

  1. Import datetime module

    Python’s datetime module provides functions that handle many complex functionalities involving the date and time. Import datetime class using a from datetime import datetime statement.

  2. Use strftime() function of a datetime class

    Use datetime.strftime(format) to convert a datetime object into a string as per the corresponding format.
    The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

  3. Use strftime() function of a time module

    Use this step if you want to convert a time object to string format. like, hours minutes seconds (hh:mm:ss). Use the time.strptime(string[, format]) function to convert a time object to a string format.