Everything You Should Know on Python Datetime Now

Python has various libraries for dealing with time and date. In this article, we will be discussing the datetime module and how the Python DateTime now function is used.

About the Module

The DateTime module provides date and time, manipulation classes. The DateTime module is a powerful library that allows us to deal with dates and times of different formats. This library will enable us to represent any timezone in the world. The datetime module has two different types of objects:

Aware Object

The aware object identifies itself to the rest of the time objects relatively. It makes use of parameters such as time zones and daylight saving.

Naive Object

The naive object does not consist of proper parameters. Other datetime objects cannot identify naive objects.

Importing the Module

As of Python 3.10, datetime is part of the Python Standard Library under the Data Types category.

import datetime

About Python Datetime.now()

The function now allows us to get the current date and time. It returns your local date and time defined by the module. Try the following demonstrations using our Online Interpreter.

Syntax

datetime.now(tz)

Parameters

Time Zone (TZ) is the required time zone to be specified. “Greenwich Mean Time (GMT)” is the default parameter. Therefore, it is an optional parameter.

Returns

Provides us the current date and time in said format.

Displaying The Current Date & Time

Using Python DateTime now function, you can display the local date and time.

import datetime

datetimeObject = datetime.datetime.now()
print(datetimeObject)

Output

2022-04-21 12:06:34.751002

Using a Python Datetime Object to Retrieve Specific Date & Time Info

Using a single DateTime object, this is all the information we can get.

datetimeObj = datetime.datetime.now()

print(datetimeObj)
print("Year: ", datetimeObj.year)
print("Month: ", datetimeObj.month)
print("Date: ", datetimeObj.day)
print("Hour: ", datetimeObj.hour)
print("Minute: ", datetimeObj.minute)
print("Second: ", datetimeObj.second)
print("TimeZone info: ", datetimeObj.tzinfo)

Output

2022-04-21 12:16:52.892221
Year:  2022
Month:  4
Date:  21
Hour:  12
Minute:  16
Second:  52
TimeZone info:  None

Displaying the Time Without Milliseconds

It is possible to format the displayed time in DateTime. Any required format but be specified using the format specifiers.

import datetime
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

Output

2022-04-23 11:11:33

How to Convert Python DateTime object to Milliseconds from Unix Time

Using the method timestamp we are able to retrieve the number of seconds since Unix Time.

import datetime
secondsUNIX = datetime.datetime.now().timestamp()
print(secondsUNIX)

Output

1650528645.570106

Converting to ISO Time Format

Using the .isoformat() function, we are able to display the time in ISO format.

import datetime
print(datetime.datetime.utcnow().isoformat())

Output

2022-04-21T11:29:49.611867

.now() Not Defined (ERROR)

Users may miss out on the fact that it is a method and not a class itself. Therefore, it must be used as a single function call.

The following code attempts to display the date in MM/DD/YYYY format.

from datetime import datetime
print str(now.month) + "." + str(now.day) + "." + str(now.year)

Error Output

name 'now' is not defined

The solution

now is not defined in the code.

from datetime import datetime
now = datetime.now()

How to Add Hours Using Python DateTime

Addition and subtraction of hours can be used in situations that require ETA. Arithmetic calculations lead to more accuracy rather than predicting manually.

In this demonstration, we are adding 10 hours to the current time using the timedelta class.

from datetime import datetime, timedelta

currentTimePlus10 = datetime.now() + timedelta(hours=10)

Output

2022-04-24 02:55:04.107059

How To Add Minutes Using Python DateTime

Similar to adding hours, we can also add minutes to the current time using the timedelta class.

Adding 10 minutes to the current time:

from datetime import datetime, timedelta

currentTimePlus10 = datetime.now() + timedelta(minutes=10)
print(currentTimePlus10)

Implementing Mocks in Python

Mocks in Python are used for unit testing applications with external dependencies. Mocks are created in order to focus on the actual program rather.

The following program attempts to create a mock for the function. datetime.date.today().

import mock
@mock.patch('datetime.date.today')
def today(cls):
    ....
    return date(2010, 1, 1)
   ...
   ...
from datetime import date
date.today()

Output

datetime.date(2010, 12, 19)

Zulu / Zero Offset in Python UTC DateTime Objects

The datetime module doesn’t recognize military timezone calls such as Zulu. However, using str.replace function we can achieve the same effect.

import datetime
dt = datetime.datetime(2022, 4, 23, 12, 0, 0)
str(dt).replace('+00:00', 'Z')

print(dt)

How to Convert One Time Zone to Another

Time Zone conversion is an essential feature that this module provides. Using the .astimezone function we can achieve such requirements.

The following program converts from UTC to America/Los Angeles

from datetime import datetime, timezone, ZoneInfo

dt_UTC = datetime.now(timezone.utc)
dt_LA = dt_UTC.astimezone(tz=datetime.ZoneInfo("America/Los_Angeles"))

print(dt_LA) 

Output

2022-04-23 05:00:39.232144

Solution

In the above program, mock.patch replaces the function datetime.date.today() with a mock object only if it’s present within the function decorator. Therefore try writing it like this:

import datetime
class NewDate(datetime.date):
    @classmethod
    def today(cls):
        return cls(2022, 23, 03)
datetime.date = NewDate

How to Create a File Name which has the Current Date and Time?

There are situations where documents or files must be categorized based on the date and time created. For example, orders from customers can be tracked on a day-to-day basis using this method.

Here’s the following Implementation for creating file names with the current date and time information.

import sys
from datetime import datetime

fileName = datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")

sys.stdout = open(fileName + '.xml', 'w')

Python time.localtime vs datetime.now

time.localtimedatetime.now
Using the time module, we can obtain the time of a record.DateTime also has the feature but only for each day.
The time module is considered to be more precise with its dataDateTime stores a particular date and time of a record.
The time module is recommended over DateTime due to ambiguity with DSTDateTime module has similar features to the time module. It provides more object-oriented data types. The only downside is that it has limited support for time zones.

Python datetime.now() vs datetime.today()

datetime.now()datetime.today()
Takes time zone (TZ) as an argumentDoesn’t take any arguments
Provides the local date and time.Also provides the local date and time.
If no argument is passed, it provides the same result as .today()Functions similar to .now(). However, .today() is more accurate.

How to Truncate the Time on a DateTime Object?

The following demonstration shows how we can truncate a DateTime object. The output provided is also a DateTime object.

import datetime
dt = datetime.datetime.now()
dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) 
print(dt)

Output

2022-04-21 00:00:00

FAQs on Python Datetime Now

How to round off python DateTime now to the nearest second?

There isn’t a particular function for rounding off. However, replacing the microseconds to the nearest 10th works.

roundedTime = raw_datetime.replace(microsecond=0)

How to get DateTime now without spaces?

Using formatting we are able to achieve this.

Example:
datetime.datetime.now().strftime("%Y%m%d%H%M%S")

How to subtract/minus one day from DateTime now?

Passing -1 in the .AddDays function will subtract one day.

dateForButton = DateTime.Now.AddDays(-1)

Conclusion

We have demonstrated the functionality of the .now() function. Other functions of the DateTime library have been discussed. The versatility of this module has been demonstrated through numerous examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments