Formatting Dates in Python

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 liberty called datetime. It consists of class and methods that can be used to work with data and time values.

To use it, first import datetime library by:

import datetime

We can have the following components in datetime:

  • The time class

    Time values can be represented using the time class. The attributes for the time class include the hour, minute, second and microsecond. One Example of time is given as follows:

    Syntax:



    time(hour, minute, second, microsecond)
    

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

    02:25:50.000013
    

    There are ranges for the time attributes i.e for seconds we have the range between 0 to 59 and for nanosecond range is between 0 to 999999. If the range exceeds, the compiler shown 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.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

  • The date class



    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:

    date(yyyy, mm, dd)
    

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

    Date date is  12  day of  5  of the year  2018
    

    To get the 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.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

Converting dates to string

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:

time.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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

May 12 2018 02:25:50

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output



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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Output

    132
    

Conversion from string to date

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output

2019-05-05 00:00:00

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.