storks
storks

Reputation: 429

Change localtime from UTC to UTC + 2 in python

How I can change this code from localtime UTC to UTC+2. Now hours() function print 13 but I need to write 15.

import time;


def hours():
    localtime =  time.localtime(time.time())
    return localtime.tm_hour


def minutes():
    localtime =  time.localtime(time.time()) 
    return localtime.tm_min

def seconds():
   localtime =  time.localtime(time.time())     
   return localtime.tm_sec


print(hours())
    #minutes()
    #seconds()

Upvotes: 2

Views: 6292

Answers (2)

Edwin Torres
Edwin Torres

Reputation: 2864

How about using the datetime module:

import datetime;

today = datetime.datetime.now()
todayPlus2Hours = today + datetime.timedelta(hours=2)

print(todayPlus2Hours)

print(todayPlus2Hours.hour)
print(todayPlus2Hours.minute)
print(todayPlus2Hours.second)

Upvotes: 3

O Green
O Green

Reputation: 27

You can use pytz along with datetime modules. for a timezone reference i'd look here. I'd do something of this sort:

import datetime
import pytz
utc_dt = datetime.datetime.now(tz=pytz.utc)
amsterdam_tz = pytz.timezone("Europe/Amsterdam")
local_amsterdam_time = amsterdam_tz.normalize(utc_dt)
print local_amsterdam_time.hour
print local_amsterdam_time.minute
print local_amsterdam_time.second

Upvotes: 3

Related Questions