Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert local time to another time zone

Tags:

python

time

I want to convert the current time to +0900 in Python.

What's the appropriate way to do this (assuming in the time module)?

I've read this isn't included with Python and you have to use something like pytz.

I don't want to change it on a server basis or globally, just in this one instance.

like image 678
Zeno Avatar asked Mar 12 '11 05:03

Zeno


4 Answers

Example for converting data from UTC to IST

from datetime import datetime
from pytz import timezone

format = "%Y-%m-%d %H:%M:%S %Z%z"

# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(format)
Output: 2015-05-18 10:02:47 UTC+0000

# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print now_asia.strftime(format)
Output: 2015-05-18 15:32:47 IST+0530
like image 51
AlvaroAV Avatar answered Sep 30 '22 02:09

AlvaroAV


I want to convert the current time to +0900 in Python ...
I don't want to change it on a server basis or globally, just in this one instance.

To get current time for +0900 timezone offset from UTC:

from datetime import datetime, timedelta

current_time_in_utc = datetime.utcnow()
result = current_time_in_utc + timedelta(hours=9)

Don't use aware datetime objects unless you also use pytz library otherwise you might get wrong results due to DST transitions and other timezone changes. If you need to do some arithmetics on datetime objects; convert them to UTC first.

like image 29
jfs Avatar answered Sep 30 '22 02:09

jfs


You can use the datetime module instead. Adapted from http://docs.python.org/library/datetime.html#datetime.tzinfo.fromutc

from datetime import tzinfo, timedelta, datetime

class FixedOffset(tzinfo):
    def __init__(self, offset):
        self.__offset = timedelta(hours=offset)
        self.__dst = timedelta(hours=offset-1)
        self.__name = ''

    def utcoffset(self, dt):
        return self.__offset

    def tzname(self, dt):
        return self.__name

    def dst(self, dt):
        return self.__dst

print datetime.now()
print datetime.now(FixedOffset(9))

Gives:

2011-03-12 00:28:32.214000
2011-03-12 14:28:32.215000+09:00

When I run it (I'm UTC-0500 for another day, then DST begins)

like image 44
Nick T Avatar answered Sep 30 '22 04:09

Nick T


Just in case you can use pytz and other external modules, this is a more straight forward solution

pip install pytz tzlocal

then

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

#timezones
local = get_localzone()
utc = pytz.utc
cet = timezone('CET')

#get now time in different zones
print(datetime.now(local))
print(datetime.now(cet))
print(datetime.now(utc))

#convert local time now to CET
print(datetime.now(local).astimezone(cet))
print(datetime.now(cet).astimezone(utc))
like image 45
aminalid Avatar answered Sep 30 '22 03:09

aminalid