how to findout local time using utcoffset and countryname in python
I have countrynames and utcoffset of that country开发者_StackOverflow How to find out out local time in that country using utcoffset?
Check out pytz for looking up timezones by location. Maybe something like this:
>>> import pytz, datetime
>>> pytz.country_timezones['de']
['Europe/Berlin']
>>> matching_tzs = [t for t in pytz.country_timezones['de'] if pytz.timezone(t)._utcoffset.total_seconds() == 3600]
>>> datetime.datetime.now(tz=pytz.timezone(matching_tzs[0]))
datetime.datetime(2011, 5, 6, 17, 5, 26, 174828, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
call datetime.now()
with the time zone (as a tzinfo
object) as an argument.
A country may span several timezones. A utc offset for a place may change through the time.
Given a country code and a utc offset, you could try to find matching timezone from Olson tz database for the current time. Here's variant of @Mu Mind's answer that takes into account current time (otherwise the result can be unexpected for some timezones):
from datetime import datetime, timedelta
import pytz
country_code, utc_offset = 'de', timedelta(hours=1)
# find matching timezones and print corresponding local time
now_in_utc = datetime.now(pytz.utc)
for zonename in pytz.country_timezones[country_code]:
tz = pytz.timezone(zonename)
local_time = now_in_utc.astimezone(tz)
if tz.utcoffset(local_time) == utc_offset: #NOTE: utc offset depends on time
print("%s\t%s" % (tz.zone, local_time.strftime("%Y-%m-%d %H:%M:%S %Z%z")))
Output
Europe/Berlin 2013-12-02 20:42:49 CET+0100
Save the current TZ
environ variable value and then do
>>> os.environ['TZ'] = 'US/Eastern'
>>> time.tzset()
And for the library, whatever time function you use will be for the US/Eastern timezone, you c can reset it back to original one later.
Example usage:
>>> time.strftime('%X %x %Z')
'22:54:11 05/06/11 SGT'
>>> os.environ['TZ'] = 'US/Eastern'
>>> time.strftime('%X %x %Z')
'10:54:30 05/06/11 EDT'
Please refer to time module documentation for examples.
working code
utcoffset='+5:30'
utctime=datetime.datetime.utcnow()
hr=utcoffset[0:utcoffset.find(':')]
min=utcoffset[utcoffset.find(':')+1:]
datetimeofclient=datetime.timedelta(hours=int(hr),minutes=int(min))
精彩评论