How to Get the Current Date and Time in Python

March 12, 2024

Introduction

Python is a versatile programming language that allows users to work on complex projects. Its simplicity, readability, extensive libraries, strong community support, and cross-platform compatibility make it ideal for rapid development, data analysis, AI, and web applications.

In this tutorial, you will learn how to get the current date and time using Python.

How to get the current date and time in Python - a tutorial.

Prerequisites

Get Current Date and Time in Python with datetime Module

The datetime module in Python lets you change dates, times, timedeltas (differences between two dates or times), timezones, and more. It allows for manipulating specific dates and times, formatting, and performing arithmetic operations with them.

This section shows different ways of using datetime to get the current date and time.

Get Current Date with datetime

Follow the steps below to create a Python script and get the current date using the datetime module:

1. Open the terminal and run the command below:

sudo nano python_date.py

The system creates a new, empty file.

2. Paste the code below into the script:

from datetime import date 
today = date.today()
print("Today's date:", today)

3. Save and exit the file.

4. Run the file with the command:

python3 python_date.py

The output shows today's date using the datetime module:

Get current date with datetime module in Python.

Note: The latest stable Python version at the time this article was Python 3.12. In Linux, python is an alias or symlink that points to the default version of Python 2.x, while python3 is an alias or symlink pointing to the default version of Python 3.x. See how to check your Python version.

Get Date and Time with datetime

Python has a number of options to configure the way date and time are formatted. Follow the steps below:

1. Create a new Python script file:

nano sample_format.py

2. Paste the following lines:

import datetime
e = datetime.datetime.now()
print ("Current date and time = %s" % e)
print ("Today's date:  = %s/%s/%s" % (e.day, e.month, e.year))
print ("The current time is: = %s:%s:%s" % (e.hour, e.minute, e.second))

3. Save the file and exit.

4. Run the file:

python3 sample_format.py

The system displays the date and time, the date, and the time in three separate lines:

Get current date and time in Python.

Get Timezone with datetime

The timezones are defined in the pytz library. Follow the steps below to print the timezone in Python:

1. Create a new script file:

sudo nano timezone.py

2. Paste the following lines:

import datetime
import pytz
def get_current_timezone():
    now = datetime.datetime.now()
    timezone = pytz.timezone(pytz.country_timezones['US'][0])  
    # You can change 'US' to your desired country code
    current_timezone = now.astimezone(timezone)
    return current_timezone.tzinfo
current_timezone = get_current_timezone()
print("Current timezone:", current_timezone)

3. Save and exit the file.

4. Run the file:

python3 timezone.py
Get the current timezone in Python.

The output shows the time in the selected timezone.

Get Time and Date Using strftime

The strftime method accepts several formatting options. This example shows how to get the current time and date and specify a format for the output. Follow the steps below:

1. Create a new script file:

nano test_format.py

2. Paste the following lines:

import datetime

e = datetime.datetime.now()

print (e.strftime("%Y-%m-%d %H:%M:%S"))

print (e.strftime("%d/%m/%Y"))

print (e.strftime("%I:%M:%S %p"))

print (e.strftime("%a, %b %d, %Y"))

3. Save the file and exit.

4. Run the file by typing:

python test_format.py
Get time and date in Python in multiple formats.

The output shows the date and time in multiple formats.

Note: The strftime method has many formatting options. All the available options are in the official documentation.

Get Current Time in Python with time Module

The time module in Python provides various time-related functions, such as getting the current time, converting between different time formats, and measuring time intervals. It operates primarily with time in seconds since the epoch (January 1, 1970).

In contrast with the time module, the datetime module offers higher-level functionalities for working with dates and times, all in a more user-friendly interface.

The following sections show how to get the current time in Python using the time module.

Get Time with strftime

The strftime method returns a string displaying the date and time using a date, time, or datetime object. Follow the steps below:

1. Create a new script using the command below:

nano python_time.py

2. Depending on your needs, you can choose to display the time in a 24-hour or 12-hour format.

To display the time in a 24-hour format, paste the following lines:

import time
print (time.strftime("%H:%M:%S"))

Alternatively, to display the time in a 12-hour format, paste the following:

import time

print (time.strftime("%I:%M:%S"))

3. Save the changes and close the file.

4. Execute the script by running:

python3 python_time.py

The result displays the time in the requested format:

Get current time in Python with the time module.

Get Time in Milliseconds

If you need a more accurate value, you can use the time module to display time in milliseconds. Follow the steps below:

1. Create a new script:

nano milliseconds.py

2. Paste the following lines:

import time
 
millisec = int(round(time.time() * 1000))
 
print("The time in milliseconds is: ", millisec)

3. Save and exit the file.

4. Run the script:

python3 milliseconds.py
Get time in Python in milliseconds.

This script utilizes the time module to obtain the current time in seconds since the epoch and then converts it to milliseconds.

Get Time in Nanoseconds

To get an even more accurate reading, you can display time in nanoseconds. Follow the steps below:

1. Create a new script:

nano nanoseconds.py

2. Paste the following lines:

import time
nanosec = time.time_ns()
print("Time in Nanoseconds:", nanosec)

Note: The time.time_ns() function is available in Python 3.7 and later.

3. Save and exit the file.

4. Run the file:

python3 nanoseconds.py
Get time in Python in nanoseconds.

Conclusion

This guide showed you how to use Python to display the date and time. Python is straightforward and offers multiple options (%X values) to show the date and time in different formats.

Next, find out how to set up time synchronization on Debian or learn the difference between R and Python.

Was this article helpful?
YesNo
Vladimir Kaplarevic
Vladimir is a resident Tech Writer at phoenixNAP. He has more than 7 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His articles aim to instill a passion for innovative technologies in others by providing practical advice and using an engaging writing style.
Next you should read
How to Install Latest Version Of Python 3 on CentOS 7
March 12, 2019

Python is a popular, stable, and well-performing programming language. CentOS 7 uses Python 2.7.5, but as...
Read more
How To Install PIP on Debian 9
October 30, 2023

Pip means "preferred installer program" or "Pip installs packages." It simplifies the installation and...
Read more
How To Install Python 3 on Windows 10
December 5, 2023

Unlike most Linux distributions, Windows does not come with the Python programming language by default...
Read more
How to Check Python Version in Linux, Mac, & Windows
December 15, 2023

Python is a popular programming language with different versions organized by release date...
Read more