I have many datetime.datetime object like 2021-06-25 15:00:08+00:00
where the timezone is different for different data.Eg.another data is 2021-06-24 06:33:06-07:00
.I want to save all of them by converting into a local tmezone.How can I do that?
How to convert datetime like `2021-06-25 15:00:08+00:00` to local timezone datetime.datetime python?
2 Answers
The datetime.datetime.astimezone()
method will return a datetime
object with the same UTC time but in the local timezone. For your example times:
>>> dt_1 = datettime.fromisoformat(2021-06-25 15:00:08+00:00)
>>> dt_1.astimezone()
datetime.datetime(2021, 6, 25, 11, 0, 8, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000), 'EDT'))
>>> dt_2 = datetime.fromisoformat(2021-06-24 06:33:06-07:00)
>>> dt_2.astimezone()
datetime.datetime(2021, 6, 24, 9, 33, 6, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000), 'EDT'))
Since datetime.datetime
objects with tzinfo
are timezone-aware, the information will be stored in the objects regardless. This is just a handy way to get the local time.
UPDATE, based on a follow-up question below:
astimezone()
doesn't depend on the way the datetime
object is created. For differently formatted date/time strings, datetime.strptime
can be used to create a timezone-aware datetime
objects. From the example given in that follow-up question:
>>> dt_3 = datetime.strptime('Sat, 26 Jun 2021 15:00:09 +0000 (UTC)',
'%a, %d %b %Y %H:%M:%S %z (%Z)')
>>> dt_3.astimezone()
datetime.datetime(2021, 6, 26, 11, 0, 9, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000), 'EDT'))

- 331
- 1
- 7
You could use pytz library
from datetime import datetime
import pytz
dt_input = datetime.fromisoformat('2021-06-24 06:33:06-07:00')
print(dt_input) # prints datetime in input timezone
local_tz = pytz.timezone('Asia/Kolkata') #provide your timezone here
dt_local = dt_input.astimezone(local_tz)
print(dt_local) #prints in your local timezone as provided above
You can refer to this SO question similar to your question:
How to convert a UTC datetime to a local datetime using only standard library?
EDIT: Convert any string to datetime object:
You can use strptime('datestring', 'dateformat')
example from your comment:
#This will convert the string to datetime object
datetime.strptime('Sat, 26 Jun 2021 15:00:09 +0000 (UTC)','%a, %d %b %Y %H:%M:%S %z (%Z)')
Once it is converted to datetime object you can convert it to your local timezone as mentioned above

- 1
- 3
-
Hey, Thanks. What about converting Sat, 26 Jun 2021 15:00:09 +0000 (UTC) to datetime.datetime object in local timezone? – Jun 26 '21 at 15:32
-
@Prabin if this formatting doesn't work for you then you may refer [link](https://www.programiz.com/python-programming/datetime/strptime) to look for more formatting options – Chaitya Chheda Jun 26 '21 at 16:09