Register Login

Python DateTime Format

Updated Apr 04, 2023

Python provides various objects, libraries, and packages that users can use to format dates and times. Examples of Python objects that users commonly use are dates and times, but using the date types which is hard to format due to their complexities without using exemplary techniques.

However, users get a great workflow using the Python date objects making it extremely easy to format date and time in the required datetime format. This article will highlight all the possible ways to convert the datetime format with suitable code snippets and explanations.  

Date and Time Formatting:

In Python, a date is not a data type, but users can use a Python module called datetime to format the dates as date objects. Importing the datetime module and correctly displaying the format of dates and times to the end-users if their application exposes these formats is one of the typical practices and a critical component of UX.

Users can represent date and time in various styles like 03-26-2023, the numerical format of datetime. On the other hand, users can also format datetime in a longer textual format, like Mar 26, 2023. Further, we can pass time in the format to display the current time.

There are several ways to format the datetime, which the article will mention in the following sections.

The datetime Module in Python:

Using the datetime module, users can manipulate the dates and times in different formats. It provides six classes that allow users to use dates and times in several applications. These are the six classes of this Python module, i.e., date, time, datetime, timedelta, timezone, and tzinfo.

Syntax:

class datetime.date(year, month, day)

Example 1: Using datetime module in traditional approach

Python datetime module provides methods allowing users to operate the date and time values.

Code:

import datetime
a_date = datetime.time(5, 35, 20, 2)
print(a_date)
print('Microsecond:', a_date.microsecond)
print('Seconds:', a_date.second) 
print('Minutes:', a_date.minute) 
print('hour:', a_date.hour)

Output:

Explanation:

In the example, we first imported the datetime module and represented the time values utilizing the time class. The time class has four attributes, hour, minute, second, and microsecond. Here, we initialized a time object with - 2 milliseconds, 20 seconds, 35 minutes, and 5 hours.

Example 2: Using datetime module with today() method

The Python today() method of the date class inside the datetime module helps to get the current date. It returns the current local date.

Syntax:

date.today()

Code Snippet:

import datetime
a_date = datetime.date.today()
print(a_date)

Output:

Explanation:

As we can see, the today() method of the date class returns the current date.

Example 3: Using datetime module with ctime() method

The ctime() method in Python allows users to convert the given time in seconds since the epoch to a string represents local time.

Syntax:

time.ctime([ sec ])

Code Snippet:

import datetime
a_date = datetime.date.today()
print(a_date)

Output:

Explanation:

We used the ctime() method for only formatting the dates and not the time. It returns the current date with the time as 00. The ctime() method returns a longer date-time structure. Users can primarily use this method to convert Unix-time to a string format.

Example 4: Using datetime module with date class to print year, month and day

Code Snippet:

import datetime
a = datetime.date.today()
print(a)
print('Current year is:', a.year)
print('Current month is:', a.month)
print('Current day is :', a.day)

Output:

Explanation:

We display the current year, month, and day using the date class of the datetime module.

Example 5: Parsing the date string to datetime format

Code Snippet:

from dateutil.parser import parse
a= parse('26, March 23, 2023, 02:00pm')
print(a)

Output:

Example 6: Using strftime() to convert dates to strings

Also, users can use the strftime() method to convert date and time objects to their string expression.

Syntax:

strftime(format, time)

Parameters used:

It accepts two parameters. The first parameter specifies the format string, and the second time specifies the formatted time (it is optional).

Code Snippet:

import datetime
a_date = datetime.datetime(2023, 3, 26)
print(a_date.strftime("%b %d %Y %H:%M:%S"))

Output:

Explanation:

In the above code snippet, we used the following string characters while formatting the data:

  • %b: This string character returns the month name with the first three letters. From our example, we get "Mar."
  • %d: This string character returns a day of the month, from 1 to 30 or 1 to 31. From our example, we get "26."
  • %Y: This string character returns a year in a four-digit format. From our example, we get "2023."
  • %H: This string character returns the hour. From our example, we get "00."
  • %M: This string character returns the minute from 00 to 59. From our example, we get "00."
  • %S: This string character returns the second from 00 to 59. From our example, we get "00."

Note: Since we have not specified the time explicitly, the strftime() will not display the time.

Example 7: Using strftime() to convert dates and times to strings

Now we will pass the time formatting the time into strings.

Code Snippet:

import datetime
a_date = datetime.datetime(2023, 3, 26, 2, 55, 32)
print(a_date.strftime("%b %d %Y %H:%M:%S"))

Output:

Example 8: Using strftime() to convert dates and times to strings in any format you want

In this example, we will show how to convert dates and times in strings using different string characters and in any format.

Code Snippet:

import datetime
a_date = datetime.datetime(2023, 3, 26)
print(a_date.strftime('%b/%d/%Y'))
print(a_date.strftime('%B'))
print(a_date.strftime('%Y'))
print(a_date.strftime('%y'))
print(a_date.strftime('%m'))
print(a_date.strftime('%p'))
print(a_date.strftime('%j'))
print(a_date.strftime('%W'))

Output:

Explanation:

In the above code snippet, we used the following string characters while formatting the data:

  • %a: This string character returns the weekday name with the first three letters. For example - Fri.
  • %A: This string character returns the full name of the weekday. For example - Friday.
  • %B: This string character returns the full name of the month. For example -  March.
  • %w: This string character returns the weekday as a number, from 0 to 6, where Sunday is 0.
  • %m: This string character returns the month as a number, from 01 to 12.
  • %p: This string character returns AM/PM for time.
  • %y: This string character returns the year in two-digit format (without the century). For instance: convert “23” instead of "2023".
  • %f: This string character returns a microsecond from 000000 to 999999.
  • %Z: This string character returns the timezone.
  • %z: This string character returns the UTC offset.
  • %j: This string character returns the day number in a year in three-digit format, from 001 to 366.
  • %W: This string character returns the week number in a year in two-digit format, from 00 to 53. Monday is the first day of the week.
  • %U: This string character returns the week number in a year in two-digit format, from 00 to 53. Sunday is the first day of each week.
  • %c: This string character returns the local date and time version.
  • %x: This string character returns the local version of the date.
  • %X: This string character returns the local version of time.

Example 9: Using datetime.strptime() to convert dates and times to strings

The strftime() method allows users to format date objects into readable strings. It is practical when users receive a string-formatted date and wish to change the format to another string-formatted date.

Users can access the parsed structure, which they can reformat to another format by converting to an intermediary datetime object.

Syntax:

datetime.strptime(string, format)

Parameter used:

It accepts two parameters. The string parameter specifies the value in string format that users will convert to date format. And the format parameter is the directive that specifies the date format after the conversion.

Code Snippet:

from datetime import datetime
a_date = '3/26/23'
demo = datetime.strptime(a_date, '%m/%d/%y')
print(demo)

Output:

Example 10: Showing ValueError in strptime()

When users pass a string as the first argument does not match the format code as a second argument, it will return a ValueError message.

Code Snippet:

from datetime import datetime
a = "26/03/2023"
b = datetime.strptime(a, "%d-%m-%Y")
print("The object of the date =", b)

Output:

Conclusion

In this Python article, we learned nearly all the ways to format a datetime using a datetime module and its classes and methods. Users can use this module for this purpose which contains six different classes. Now, it is up to the users' choice which technique they will apply to get the desired data and time format.


×