Formatting Dates in Python - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Hi everyone, In this tutorial, we will learn how to format dates in Python with many examples using the built-in datetime module that provides classes to work with dates and time. We will learn how to convert objects of date, time, datetime into a string representation and a string into datetime object using strftime() and strptime() methods.
In this section, we will see how to convert the date, time, datetime objects into their string representation.
Let’s import the datetime module and create an object of class time.
# importing datetime module
import datetime
# using time class from datetime module
# we create a time class object
ex_time = datetime.time(13,50,25,65800)
print(ex_time)
# printing the type of object
print(type(ex_time))
Output:
12:50:25.065800
<class 'datetime.time'>
The output is in format hours:minutes:seconds.microseconds. Let’s verify these by printing the attributes separately.
# Printing all attributes separately
print("Hour : ",ex_time.hour)
print("Minutes : ",ex_time.minute)
print("Seconds : ",ex_time.second)
print("Microseconds : ",ex_time.microsecond)
Output:
Hour : 13
Minutes : 50
Seconds : 25
Microseconds : 65800
Now we have a time object, its time to use strftime() method to convert it into a string. We will use some format codes to achieve all this. It is similar to how the string formatting is done. You can refer to this tutorial on string formatting to know more.
Refer to the link of Format Codes in the reference section at the end to know more about Format codes used in Date and Time formatting

 %H, %M, %S format codes

%H – Hour (24-hour clock) as a zero-padded decimal number.
%M – Minute as a zero-padded decimal number.
%S – Second as a zero-padded decimal number.


%H – Hour (24-hour clock) as a zero-padded decimal number.
%M – Minute as a zero-padded decimal number.
%S – Second as a zero-padded decimal number.
print(ex_time.strftime("%H-%M-%S"))
Output:
13-50-25

 %I, %f, %p format codes

%I – Hour (12-hour clock) as a zero-padded decimal number.
%f – Microsecond as a decimal number, zero-padded on the left.
%p – Locale’s equivalent of either AM or PM.


%I – Hour (12-hour clock) as a zero-padded decimal number.
%f – Microsecond as a decimal number, zero-padded on the left.
%p – Locale’s equivalent of either AM or PM.
print(ex_time.strftime("%I:%M:%S.%f %p"))
Output:
01:50:25.065800 PM
As we have done in the above section, in this section we will create an object of type datetime. Since format codes remain the same, By the end of this section, we will be able to format most of the dates and times.
ex_date = datetime.datetime(year=2020, month=11, day=10, hour=16, minute=38, second=40)
print(ex_date)
print(type(ex_date))
Output:
2020-11-10 16:38:40

<class 'datetime.datetime'>
We see that we have created a datetime object with defined date and time, let us see how to print the same date-time differently using other format codes.

 %d, %m, %Y format codes

%d – Day of the month as a zero-padded decimal number
%m – Month as a zero-padded decimal number.
%Y – Year with century as a decimal number.


%d – Day of the month as a zero-padded decimal number
%m – Month as a zero-padded decimal number.
%Y – Year with century as a decimal number.
print(ex_date.strftime("%d/%m/%Y %H-%M-%S"))
Output:
10/11/2020 16-38-40

 %a, %w, %y, %b format codes

%a – Weekday as locale’s abbreviated name.
%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%b – Month as locale’s abbreviated name.
%y – Year with century as a decimal number.


%a – Weekday as locale’s abbreviated name.
%w – Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.
%b – Month as locale’s abbreviated name.
%y – Year with century as a decimal number.
print(ex_date.strftime("%a %w %d-%b-%y %H-%M-%S"))
Output:
Tue 2 10-Nov-20 16-38-40

 %A, %B, %W format codes

%A – Weekday as locale’s full name.
%B – Month as locale’s full name.
%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.


%A – Weekday as locale’s full name.
%B – Month as locale’s full name.
%W – Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
print(ex_date.strftime("%A %W '%d %B %Y' %H-%M-%S %p"))
Output:
Tuesday 45 '10 November 2020' 16-38-40 PM
With these, we have finished the section and know how to convert a datetime object into a string representation using format codes. Let’s see how we can convert a string to a datetime object.
In this section, we will use the same format codes and a string to represent that string into a date-time representation. The strptime() method of datetime class from datetime module takes 2 parameters, a string of date and a format string in which we want to convert respectively. This format string is made up of the format codes that we have studied and any inappropriate conversion will lead to a value error.
import datetime

date_string1 = "15/09/20"
print(datetime.datetime.strptime(date_string1,'%d/%m/%y'))
Output:
2020-09-15 00:00:00
date_string2 = "Nov15202016-05-30"
print(datetime.datetime.strptime(date_string2,'%b%d%Y%H-%M-%S'))
Output:
2020-11-15 16:05:30
In this tutorial, we have how to format dates in Python. If you have any doubt, feel free to ask in the comment section.
Format Codes 
Different ways to do String formatting in Python
Date yyyymmdd format in Shell Script
Happy Learning 🙂

How to create Python Iterable class ?
Python Number Systems Example
Different ways to do String formatting in Python
Convert any Number to Python Binary Number
Python Operators Example
How to read JSON file in Python ?
Python How to read input from keyboard
How to Remove Spaces from String in Python
How to remove empty lists from a Python List
How to sort python dictionary by key ?
Python TypeCasting for Different Types
What are the different ways to Sort Objects in Python ?
Java 13 Text Blocks – Formatting String in Java 13
How to remove special characters from String in Python
Python – How to create Zip File in Python ?

How to create Python Iterable class ?
Python Number Systems Example
Different ways to do String formatting in Python
Convert any Number to Python Binary Number
Python Operators Example
How to read JSON file in Python ?
Python How to read input from keyboard
How to Remove Spaces from String in Python
How to remove empty lists from a Python List
How to sort python dictionary by key ?
Python TypeCasting for Different Types
What are the different ways to Sort Objects in Python ?
Java 13 Text Blocks – Formatting String in Java 13
How to remove special characters from String in Python
Python – How to create Zip File in Python ?
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list