Get Current Date and Time in Python With 2 Easy Methods

Try this guide with our instant dedicated server for as low as 40 Euros

python datetime

Working with time and date are critical aspects of building software for business and scientific applications. Most operations and actions in business operations and scientific research are dependent upon measuring time and knowing the exact time and date at any given time. 

Since Python is the language of choice for business applications, data analysis, AI, and projects that require cross-platform interoperability, knowing how to manipulate time and date is essential for building robust applications.

In this short tutorial, we will describe two methods you can apply to manipulate time and date in Python projects. 

Table Of Contents

  1. Method #1: Use the datetime Module in Python Projects
    1. Find the Current Date with the datetime
    2. Find and Print the Current Date and Time
    3. Find the Timezone
    4. Use strftime to Format the Time and Date
  2. Method #2: Use Python’s time module to Find the Current Time
    1. Convert Current Time in String
    2. Get the Time in Milliseconds
    3. Find Out the Time in Nanoseconds
  3. Conclusion
  4. FAQs

Method #1: Use the Python datetime Module in Projects

With Python datetime package, you can change dates, times, time deltas (differences between two dates or times), and time zones. It also allows formatting, mathematical operations, and the manipulation of specific dates and times. 

Let’s see how you can use this module to obtain the current date and time.

Find the Current Date with the datetime

You can use the python datetime module to find the current date through a Python script. Follow these steps to create and run the script:

  1. Launch the terminal and type the following command to create an empty Python script file with Nano:

# sudo nano python_date.py

  1. Add the following code into this file:

from datetime import date

today = date.today()

print("Today's date:", today)

print today date

  1. Close the file and save it.
  2. Use this command to launch the file:

# python3 python_date.py

python3 python_date.py

As you can see, the script prints out the current date in the terminal.

Find and Print the Current Date and Time

Finding the current date and time is an essential requirement of many Python scripts. The following Python script gets the current time and date and formats the output. Here are the steps of the process:

  1. Run the following command to create an empty Python script in Nano:

# nano sample_format.py

  1. Copy and paste these lines in the script file:

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))

import date time

  1. Close and save the file.
  2. Run the following command to launch the script:

# python3 sample_format.py

The output shows three entries – the current system date and time, date and current time.

python3 sample format.py

Find the Timezone

We recommend the pytz library to get the system’s time zone settings. Run the following steps to see this library in action:

  1. Use the following command to create a Python script file using Nano:

# sudo nano timezone.py

  1. Copy and paste these lines into the file:

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)

import pytz

  1. Close the file and save it.
  2. Launch the file by running the following command in the terminal:

# python3 timezone.py

python3 timezone.py

Use strftime to Format the Time and Date

strftime stands for string format time. It is a great option for converting the date and time into a string you can further process using Python’s string functions. The following process runs through an implementation of strftime in working with system date and time.

  1. Make a new Python script using Nano by running the following command in the terminal:

# nano test_format.py

  1. Copy and paste these lines in the script file:

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"))

import datetime

  1. Close and save the file.
  2. Run the following command to launch the file:

# python3 test_format.py

python3 test_format.py

The output shows the current time and date as strings that you can further process in your scripts. 

Our detailed overview of Python’s benefits helps you determine whether it is the right choice for your projects. 

Method #2: Use Python’s time module to Find the Current Time

Python’s time module offers a range of time-related operations, including measuring time intervals, obtaining the current time, and converting between different time formats. In its native format, it measures time in seconds from January 1, 1970.

The time module in Python can be used to obtain the current time as we will demonstrate in the following sections.

Convert Current Time in String

You can combine the strftime method to yield a string that shows the current date and time. This process has the following steps:

  1. Use the following command to create a new Python file:

# nano python_time.py

  1. Based on your needs, you can select between a 12-hour and 24-hour format for the time display.

If you opt for the 24-hour format, paste the following lines in the file:

import time

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

import time

Alternatively, you can paste the following lines to see the time in a 12-hour format:

import time

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

  1. Close and save the file.
  2. Run the script to see it in action:

# python3 python_time.py

python3 time.py

Get the Time in Milliseconds

If you need a more precise time value, we recommend the following application of the time module to display time in milliseconds.

  1. Create a fresh Python file in Nano:

# nano milliseconds.py

  1. Copy and paste these lines into the file:

import time

millisec = int(round(time.time() * 1000))

print("The time in milliseconds is: ", millisec)

  1. Close the file and save it.
  2. Launch the script in the terminal:

# python3 milliseconds.py

python3 milliseconds.py

In this script, we first get the time from the epoch and then convert it into milliseconds.

Find Out the Time in Nanoseconds

You can further drill down the time format into nanoseconds to obtain an even more precise time measurement. Here are the steps of the process:

  1. Create a new Python file:

# nano nanoseconds.py

  1. Copy and paste these lines into this file:

import time

nanosec = time.time_ns()

print("Time in Nanoseconds:", nanosec)

import time nanosec

  1. Close the file and save it.
  2. Launch the file:

# python3 nanoseconds.py

python3 nanoseconds.py

This script follows the approach of the previous section by first getting the time and then converting it into nanoseconds using the ns() method. 

Conclusion

Programmers can get the current date and time for their apps. Programmers can procure precise depictions of the present date and time in diverse forms by using modules and their corresponding functions, including datetime.now() and time.localtime(). 

Many Python applications require access to the current date and time in order to schedule tasks, log events, or show information to users. Developers can successfully integrate date and time functionality into their Python programs with the two modules we discussed in this tutorial.

Experience the power of global hosting with RedSwitches, your dedicated hosting provider. Just as Python simplifies accessing the current date and time, RedSwitches empowers your online presence with unmatched reliability, security, and performance. Choose RedSwitches today and elevate your website’s performance to new heights. With our global infrastructure and expert support, we ensure seamless hosting tailored to your needs. 

So, If you’re looking for a robust server for your Linux projects, we offer the best dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. How do I get the current date and time in Python?

The datetime.now() function in the datetime module allows you to get the current date and time in Python.

Q. Can I customize the format of the current date and time output?

The date and time output can be formatted to your liking using the strftime() technique.

Q. Does Python provide any other modules for working with dates and times?

Yes, Python offers additional modules like time and calendar for handling date and time-related operations.

Q. How accurate is the current date and time obtained from Python?

The exactness of the current date and time obtained from Python is contingent upon the accuracy of the system’s clock.

Q. Can I retrieve the current date and time in a specific time zone?

To work with time zones and find the current date and time in a particular time zone, utilize the pytz module.

Q. Are there any considerations for handling daylight saving time in Python?

Python’s datetime module automatically handles daylight saving time adjustments when working with timezones.

Q. Can I perform arithmetic operations with date and time objects in Python?

Yes, you can perform arithmetic operations like addition and subtraction on datetime objects to calculate time differences or intervals.

Q. How can I convert date and time objects to strings for display purposes?

To convert datetime objects to string representations, you can use the str() function or strftime() method.

Q. Are third-party libraries available for working with dates and times in Python?

Yes, libraries like dateutil and Arrow provide additional functionalities for working with dates and times beyond the built-in modules.

Q. Where can I find more resources and documentation for working with dates and times in Python?

The Python documentation and online resources like tutorials and forums offer extensive information and guidance for working with dates and times in Python.

Try this guide with our instant dedicated server for as low as 40 Euros