Open In App

How to remove timezone information from DateTime object in Python

Improve
Improve
Like Article
Like
Save
Share
Report

Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.

In this article, we will discuss how to remove timezone information from the DateTime object.

Functions Used

  • datetime.now(tz=None): Returns the current local date and time.
  • datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.

To remove timestamp, tzinfo has to be set None when calling replace() function.

First, create a DateTime object with current time using datetime.now(). The DateTime object was then modified to contain the timezone information as well using the timezone.utc. The DateTime object with timezone information is then manipulated using the .replace() method to remove the timezone information using the tzinfo parameter.

Syntax:

replace(tzinfo=None)

Example:

Python




from datetime import datetime, timezone
 
# Get the datetime object using datetime
# module
dt_obj_w_tz = datetime.now()
print(dt_obj_w_tz)
 
# Add timezone information to the datetime
# object
dt_obj_w_tz = dt_obj_w_tz.replace(tzinfo=timezone.utc)
print(dt_obj_w_tz)
 
# Remove the timezone information from the datetime
# object
dt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)
print(dt_obj_wo_tz)


Output: 

2021-08-10 12:51:42.093388
2021-08-10 12:51:42.093388+00:00
2021-08-10 12:51:42.09338

However, the datetime object with timestamp can be created by providing tz parameter.

Example:

Python




from datetime import datetime, timezone
 
# Get the datetime object with timezone
# information
dt_obj_w_tz = datetime.now(tz=timezone.utc)
print(dt_obj_w_tz)
 
# Remove the timezone information from the
# datetime object
dt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)
print(dt_obj_wo_tz)


Output:

2021-08-10 07:21:57.838856+00:00
2021-08-10 07:21:57.838856


Last Updated : 09 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads