-1

I've written below code in Python3.

import datetime as dt

a = dt.datetime(2020,7,24,9,0,0)
print(a)

This is showing below output.

2020-07-24 09:00:00

But it is not showing in localized format. Expected output should be as mentioned below as my timezone is 'Asia/Kolkata'.

2020-07-24 09:00:00+05:30

How to get this done?

tripleee
  • 175,061
  • 34
  • 275
  • 318
BARUN
  • 139
  • 12
  • That's not "localized", it just adds the time zone information. Localized would be something like 7/24 2020 (assuming your local convention is as crazy as the American one). – tripleee Jul 25 '20 at 11:37
  • a = dt.datetime(2020,7,24,9,0,0, tzinfo=dt.timezone(dt.timedelta(hours=5, minutes=30))) – BARUN Jul 25 '20 at 12:41

2 Answers2

0

You could do it using the pytz module, to further localize it and also show the timezone, use the module tzlocal

pip install pytz tzlocal

Code:

from datetime import datetime
from pytz import timezone
from tzlocal import get_localzone

format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to local time zone
now_local = now_utc.astimezone(get_localzone()) # ie 'Asia/Kolkata'
print(now_local.strftime(format))

Output:

2020-07-25 07:05:50 UTC+0000
2020-07-25 12:35:50 IST+0530

Also a detailed answer is given here.

faruk13
  • 1,276
  • 1
  • 16
  • 23
  • I've written below code a = dt.datetime(2020,7,24,9,0,0, tzinfo=timezone('Asia/Kolkata')) print(a) Output: 2020-07-24 09:00:00+05:53 – BARUN Jul 25 '20 at 11:48
0
import datetime as dt

a = dt.datetime(2020,7,24,9,0,0)
local_time = "+5:30"
print(str(a)+local_time)

output

2020-07-24 09:00:00+5:30