Get system date/time in Python after changing time zone
Question
On my system, I have set the current time zone for my clock to "Kuala Lumpur, Singapore (UTC+08:00)", which puts my clock forward by eight hours (of course).
In python, I'm using the code to get the current time/date:
from datetime import datetime
dateTimeTuple = datetime.now()
I'm using this method as I need the individual parts (including the micro-second).
However, it will always returns me a regular time (not eight hours in front based on the selected time zone).
Is there another method?
Solution
datetime.now()
returns a naive local datetime. To convert that to Kuala Lumpur time, you first need to make it a timezone-aware datetime, and then convert it to the Kuala Lumpur timezone:
The easiest way to do timezone conversions is to use pytz.
import pytz
import datetime as dt
kuala_lumpur=pytz.timezone('Asia/Kuala_Lumpur')
localtz=pytz.timezone('Europe/London')
Here is the naive datetime.
now = dt.datetime.now()
Use localize
to make the datetime timezone aware.
now=localtz.localize(now)
print(now)
# 2011-09-19 11:58:46.342254+01:00
Use astimezone
to convert to another timezone:
now_in_kuala_lumpur=now.astimezone(kuala_lumpur)
print(now_in_kuala_lumpur)
# 2011-09-19 18:58:46.342254+08:00
Due to Daylight Savings Time in the UK and no DST in Kuala Lumpur, the time difference is currently 7 hours.