Formatting Dates in Python - GeeksforGeeks (2024)

In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values.

Required library

import datetime

The datetime.time method

Time values can be represented using the time class. The attributes for the time class include the hour, minute, second, and microsecond.

Syntax of datetime.time

time(hour, minute, second, microsecond)

Example 1:

Python3

import datetimetm = datetime.time(2, 25, 50, 13)print(tm)

Output

02:25:50.000013

Example 2:

There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanoseconds, range is between 0 to 999999. If the range exceeds, the compiler shows a ValueError. The instance of time class consists of three instance attributes namely hour, minute, second, and microsecond. These are used to get specific information about the time.

Python3

import datetimetm = datetime.time(1, 50, 20, 133257)print('Time tm is ', tm.hour, ' hours ', tm.minute, ' minutes ', tm.second, ' seconds and ', tm.microsecond, ' microseconds')

Output

Time tm is 1 hours 50 minutes 20 seconds and 133257 microseconds

The datetime.date method

The values for the calendar date can be represented via the date class. The date instance consists of attributes for the year, month, and day.

Syntax of datetime.date

date(yyyy, mm, dd)

Example 1:

Python3

import datetimedate = datetime.date(2018, 5, 12)print('Date date is ', date.day, ' day of ', date.month, ' of the year ', date.year)

Output

Date date is 12 day of 5 of the year 2018

Example 2:

To get today’s date names a method called today() is used and to get all the information in one object (today’s information) ctime() method is used.

Python3

import datetimetday = datetime.date.today()daytoday = tday.ctime()print("The date today is ", tday)print("The date info. is ", daytoday)

Output

The date today is 2020-01-30
The date info. is Thu Jan 30 00:00:00 2020

Convertstring to date using DateTime

Conversion from string to date is many times needed while working with imported data sets from a CSV or when we take inputs from website forms. To do this, Python provides a method called strptime().

Syntax: datetime.strptime(string, format)

Parameters:

  • string – The input string.
  • format – This is of string type. i.e. the directives can be embedded in the format string.

Example:

Python3

from datetime import datetimeprint(datetime.strptime('5/5/2019', '%d/%m/%Y'))

Output

2019-05-05 00:00:00

Convert dates to strings using DateTime

Date and time are different from strings and thus many times it is important to convert the DateTime to string. For this, we use strftime() method.

Syntax of datetime.strftime

Syntax: datetime.strftime(format, t)

Parameters:

  • format – This is of string type. i.e. the directives can be embedded in the format string.
  • t – the time to be formatted.

Example 1:

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%b %d %Y %H:%M:%S"))

Output

May 12 2018 02:25:50

Example 2:

The same example can also be written in a different place by setting up the print() method.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%H:%M:%S %b %d %Y"))

Output

02:25:50 May 12 2018 

%H, %M and %S displays the hour, minutes and seconds respectively. %b, %d and %Y displays 3 characters of the month, day and year respectively. Other than the above example the frequently used character code List along with its functionality are:

Frequently used character code in DateTime

  • %a: Displays three characters of the weekday, e.g. Wed.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%a"))

Output

Sat
  • %A: Displays name of the weekday, e.g. Wednesday.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%A"))

Output

Saturday
  • %B: Displays the month, e.g. May.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%B"))

Output

May
  • %w: Displays the weekday as a number, from 0 to 6, with Sunday being 0.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%w"))

Output

6
  • %m: Displays month as a number, from 01 to 12.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%m"))

Output

5
  • %p: Define AM/PM for time.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%p"))

Output

PM
  • %y: Displays year in two-digit format, i.e “20” in place of “2020”.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% y"))

Output

18
  • %f: Displays microsecond from 000000 to 999999.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("% f"))

Output

000013
  • %j: Displays number of the day in the year, from 001 to 366.

Python3

import datetimex = datetime.datetime(2018, 5, 12, 2, 25, 50, 13)print(x.strftime("%j"))

Output

132


piyush25pv

Improve

Previous Article

Python program to print current year, month and day

Next Article

Python calendar module : iterweekdays() method

Please Login to comment...

Formatting Dates in Python - GeeksforGeeks (2024)
Top Articles
Can You Get Tinder Gold for Free? Find the Cheapest Price
The best gaming deals of the week: Save on 'Baldur's Gate 3,' Xbox Game Pass, and a Switch Lite bundle
Mybranch Becu
Maria Dolores Franziska Kolowrat Krakowská
Unblocked Games Premium Worlds Hardest Game
Mcfarland Usa 123Movies
Flixtor The Meg
GAY (and stinky) DOGS [scat] by Entomb
Hallowed Sepulchre Instances & More
Mikayla Campinos Videos: A Deep Dive Into The Rising Star
World of White Sturgeon Caviar: Origins, Taste & Culinary Uses
Readyset Ochsner.org
Persona 4 Golden Taotie Fusion Calculator
Guilford County | NCpedia
Craigslist Edmond Oklahoma
Craigslist Free Stuff Greensboro Nc
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Craigslist Pet Phoenix
Baja Boats For Sale On Craigslist
UMvC3 OTT: Welcome to 2013!
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Il Speedtest Rcn Net
Boise Craigslist Cars And Trucks - By Owner
Finding Safety Data Sheets
Costco Jobs San Diego
Catchvideo Chrome Extension
How do you get noble pursuit?
Pixel Combat Unblocked
TMO GRC Fortworth TX | T-Mobile Community
Top Songs On Octane 2022
How Do Netspend Cards Work?
Roadtoutopiasweepstakes.con
Grandstand 13 Fenway
Appleton Post Crescent Today's Obituaries
Cross-Border Share Swaps Made Easier Through Amendments to India’s Foreign Exchange Regulations - Transatlantic Law International
Obsidian Guard's Skullsplitter
Buhsd Studentvue
The best Verizon phones for 2024
Instafeet Login
Oriellys Tooele
Conroe Isd Sign In
877-292-0545
Thelemagick Library - The New Comment to Liber AL vel Legis
Atom Tickets – Buy Movie Tickets, Invite Friends, Skip Lines
The power of the NFL, its data, and the shift to CTV
How I Passed the AZ-900 Microsoft Azure Fundamentals Exam
Reli Stocktwits
Lesly Center Tiraj Rapid
8 4 Study Guide And Intervention Trigonometry
Identogo Manahawkin
Superecchll
Competitive Comparison
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 6021

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.