How to get the UTC offset from a timezone string using pytz? - python

I am trying to get the UTC offset as a string from my timezone using the Python library pytz.
I am defining it as follows:
import pytz
tz = pytz.timezone('Africa/Cairo')
Now, I want to get '+02:00' from the tz variable, as that is the corresponding UTC offset for Africa/Cairo.
How can I do this? Thanks!

You can use datetime to get current date/time in given timezone and then extract UTC offset,
import pytz
import datetime
tz = pytz.timezone('Africa/Cairo')
print(datetime.datetime.now(tz).utcoffset().total_seconds()/3600)
# output,
2.0

Related

Convert "PST" to "US/Pacific" for use with Pytz

I'm trying to create HTTP endpoints:
one that returns posts to a user that were created in a given month in the requestor's time zone.
another one that gets the months possible for post*.
Examples
(1) get posts in month of requestor's timezone
(2) get possible months for posts
For example if the user made posts in Sept-November but none in December then Jan onward it wouldn't return December.
But it takes the time zone in "PST" format, because it does a SQL query.
Problems
Unfortunately pytz, the library I'm using for getting all posts from a month, only accepts time zone in the format "US/Pacific".
Questions
What is the format or string representation "US/Pacific" called ?
How can I convert the string formats "PST", "UCT" or "CST" to their respective formats like "US/Pacific", etc. in Python ?
What's the name for this format like "US/Pacific" ?
Is there a sort of dictionary that maps "PST" to "US/Pacific" ?
Time zone terminology
How to define, represent or refer to a time zone? Some terms:
UTC time offset (e.g. "UTC-08:00")
in relation with ISO 8601 date/time format: time zone designator (e.g. "Z" or "-08")
time zone: canonical name
time zone: abbreviation
(Canonical) names
The spelled-out time zone names or (tz names) like "US/Pacific" or "Europe/Paris" are also called canonical names of time zone. They are used as key in the IANA time zone database. In RFC 6557 they are referred to as "time zone names". Wikipedia claims about them:
The primary, preferred zone name.
See also:
ECMA: 6.4Time Zone Names
Abbreviations
The alphabetic string literals like "UTC", "PST" are abbreviations of time zone.
Conversion between time zones
Usually the conversion between time zones is done by modifying the offsets of UTC which are represented in ISO 8601, time zone designators like "-0800" (PST) which is 8 hours subtracted from "+0000" (UTC).
See also:
Daylight saving time and time zone best practices
Converting using pytz timezone
To convert a given date-time from UTC to the target time zone (e.g. "US/Pacific") use astimezone(tz) on the source date-time instance:
import datetime
from pytz import timezone, utc
utc_time = datetime.datetime.utcnow()
pst_tz = timezone('US/Pacific')
pst_time = utc_time.replace(tzinfo=utc).astimezone(pst_tz)
Note:
the time-zone tz is built using pytz's tzinfo API, e.g. with timezone('PST8PDT') for PST or timezone('US/Central') for CST
the .replace() is optional and resets the time zone of given date-time to default UTC.
Surprisingly: The "PST" abbreviation is not found in pytz.all_timezones. Most similar are (evaluated in REPL):
>>> import pytz
>>> pytz.timezone('PST8PDT')
<DstTzInfo 'PST8PDT' PST-1 day, 16:00:00 STD>
>>> pytz.timezone('US/Pacific')
<DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>
>>> pytz.timezone('US/Central')
<DstTzInfo 'US/Central' LMT-1 day, 18:09:00 STD>
See also:
pytz - Converting UTC and timezone to local time
Is there a list of Pytz Timezones?
Converting using zoneinfo (since 3.9)
Adjusted from MrFuppes answer to "How do I use timezones with a datetime object in python?":
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_time = datetime(2012,11,10,9,0,0, tzinfo=timezone.utc)
cst_tz = ZoneInfo("US/Central")
cst_time = utc_time.astimezone(cst_tz)
# safely use `replace` to get the same wall time in a different tz:
pst_time = cst_time.replace(tzinfo=ZoneInfo("US/Pacific"))
print(utc_time.isoformat())
print(cst_time.isoformat())
print(pst_time.isoformat())
(above code is not tested!)
See also:
new Python module zoneinfo — IANA time zone support
Paul Ganssle (2021): Stop using utcnow and utcfromtimestamp, blog article from the maintainer of python-dateutil
import pytz
from datetime import datetime # timezone
print('The supported tz:', pytz.all_timezones, '\n')
# Show date-time for different timezone/country
# current date and time of NY
datetime_NY = datetime.now(pytz.timezone('America/New_York'))
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))
# NY: 07/28/2021, 05:49:41
# Timezone Conversion
# Any timezone to UTC
NY_to_utc = datetime_NY.astimezone(pytz.utc)
print("NY_to_utc: ", NY_to_utc.strftime("%m/%d/%Y, %H:%M:%S"))
# NY_to_utc: 07/28/2021, 09:49:41
Naive and Aware datetime Refer this article for dealing with timezone
Show date-time for different timezone/country
Timezone Conversion
Timezone unaware/naive to Timezone aware
Issue with replace

How to use datetime.fromtimestamp() to convert the UTC time format into the correct timezone (a variable)?

I am building a weather forecast website using the Darksky API (docs: https://darksky.net/dev/docs#forecast-request), and I want to use weather.json()['currently']['timezone'] to convert the Unix time into the timezone given by the city (for example, the input was Mexico City, I want the time in Mexico City) using datetime.fromtimestamp(weather.json()['currently']['timezone']).strftime('-%H'). What more do I need to add? Or what other methods could I try to figure out with?
I tried doing simply
Time in {location}: {datetime.fromtimestamp(weather.json()['currently']['time']).strftime('%Y-%m-%d %H:%M:%S')}
Where location is the city (and yes, it is in an f string)
output was in the UTC time, but I want the time in the timezone (correctly formatted into H:M:S) that the city is in
no error message, just an output I want to manipulate (and I am new to the datetime module)
you can do so in the following way:
import datetime
import dateutil.tz as tz
import tzlocal
# dummy datetime in utc for testing
utc_time = datetime.datetime.utcnow()
#get current timezone
local_zone = tzlocal.get_localzone().zone
#build timezone information to be removed
utc_zone_info = tz.gettz("UTC")
#build local timezone information to be set
local_zone_info = tz.gettz(local_zone)
#replace utc zone info
replaced_utc = utc_time.replace(tzinfo=utc_zone_info)
#update zone info of datetime object with local timezone
result_dt = replaced_utc.astimezone(tzinfo=local_zone_info).strftime("%H:%m:%S")
P.S: You will have to install the tzlocal library via pip/conda

how to convert UTC timezone DateTime in to local timezone using Django ORM query

class Book(models.Model):
created_at=models.DateTimeField(auto_now_add=True)
this datetime is in utc timezone and I want to this datetime in to local timezone converted using query.
You can make use of pytz for this.
First, find your timezone from pytz.all_timezones (ex: Asia/Kolkata)
import pytz
book_obj = Book.objects.get(pk=1) # Replace query parameters according to your needs
my_timezone = pytz.timezone("Asia/Kolkata") # Replace Asia/Kolkata with your timezone
local_created_at = book_obj.created_at.astimezone(my_timezone)

Unix timestamp to iso 8601 time format

When I convert unix time 1463288494 to isoformat i get 2016-05-14T22:01:34. How can I get the output including the -07:00. In this format 2016-05-14T22:01:34-07:00
from datetime import datetime
t = int("1463288494")
print(datetime.fromtimestamp(t).isoformat())
You can pass a tzinfo instance representing your timezone offset to fromtimestamp(). The problem then is how to get the tzinfo object. The easiest way is to use the pytz module which provides a tzinfo compatible object:
import pytz
from datetime import datetime
tz = pytz.timezone('America/Los_Angeles')
print(datetime.fromtimestamp(1463288494, tz).isoformat())
#2016-05-14T22:01:34-07:00

pytz - Converting UTC and timezone to local time

I have a datetime in utc time zone, for example:
utc_time = datetime.datetime.utcnow()
And a pytz timezone object:
tz = timezone('America/St_Johns')
What is the proper way to convert utc_time to the given timezone?
I think I got it:
pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)
This line first converts the naive (time zone unaware) utc_time datetime object to a datetime object that contains a timezone (UTC). Then it uses the astimezone function to adjust the time according to the requested time zone.
It's the exact purpose of fromutc function:
tz.fromutc(utc_time)
(astimezone function calls fromutc under the hood, but tries to convert to UTC first, which is unneeded in your case)
I agree with Tzach's answer. Just wanted to include that the is_dst parameter is not required:
pytz.utc.localize(datetime.utcnow()).astimezone(tz)
That code converts the current UTC time to a timezone aware current datetime.
Whereas the code below converts the current UTC time to a timezone aware datetime which is not necessarily current. The timezone is just appended into the UTC time value.
tz.localize(datetime.utcnow())
May I recommend to use arrow? If I understood the question:
>>> import arrow
>>> utc = arrow.utcnow()
>>> utc
<Arrow [2014-08-12T13:01:28.071624+00:00]>
>>> local = utc.to("America/St_Johns")
>>> local
<Arrow [2014-08-12T10:31:28.071624-02:30]>
You can also use
tz.fromutc(utc_time)
Another very easy way:
Because utcnow method returns a naive object, so you have to convert the naive object into aware object. Using replace method you can convert a naive object into aware object. Then you can use the astimezone method to create new datetime object in a different time zone.
from datetime import datetime
import pytz
utc_time = datetime.utcnow()
tz = pytz.timezone('America/St_Johns')
utc_time =utc_time.replace(tzinfo=pytz.UTC) #replace method
st_john_time=utc_time.astimezone(tz) #astimezone method
print(st_john_time)
You can also use the sample below, I use it for similar task
tz = pytz.timezone('America/St_Johns')
time_difference=tz.utcoffset(utc_time).total_seconds() #time difference between UTC and local timezones in 5:30:00 format
utc_time = date + timedelta(0,time_difference)
It works fast and you don't need to import additional libraries.

Categories