How do I use timezones with a datetime object in python?

How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()

import datetime, re
from datetime import tzinfo

class myTimeZone(tzinfo):
    """docstring for myTimeZone"""
    def utfoffset(self, dt):
        return timedelta(hours=1)

def myDateHandler(aDateString):
    """u'Sat,  6 Sep 2008 21:16:33 EDT'"""
    _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
    day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
    month = [
            'JAN', 'FEB', 'MAR', 
            'APR', 'MAY', 'JUN', 
            'JUL', 'AUG', 'SEP', 
            'OCT', 'NOV', 'DEC'
    ].index(month.upper()) + 1
    dt = datetime.datetime(
        int(year), int(month), int(day), 
        int(hour), int(minute), int(second)
    )                   
    # dt = dt - datetime.timedelta(hours=1)
    # dt = dt - dt.tzinfo.utfoffset(myTimeZone())
    return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)

def main():
    print myDateHandler("Sat,  6 Sep 2008 21:16:33 EDT")

if __name__ == '__main__':
    main()


Asked by: Walter471 | Posted: 05-10-2021






Answer 1

I recommend babel and pytz when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones.

Answered by: Brad111 | Posted: 06-11-2021



Answer 2

The Python standard library doesn't contain timezone information, because unfortunately timezone data changes a lot faster than Python. You need a third-party module for this; the usual choice is pytz

Answered by: Kirsten396 | Posted: 06-11-2021



Answer 3

For the current local timezone, you can you use:

>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9

The value returned is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.

localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).

Answered by: Stella189 | Posted: 06-11-2021



Answer 4

Python >= 3.9

Python comes with zoneinfo as part of the standard lib. Example usage:

from datetime import datetime, timezone
from zoneinfo import ZoneInfo
UTC = datetime(2012,11,10,9,0,0, tzinfo=timezone.utc)

# convert to another tz with "astimezone":
eastern = UTC.astimezone(ZoneInfo("US/Eastern"))

# note that it is safe to use "replace",
# to get the same wall time in a different tz:
pacific = eastern.replace(tzinfo=ZoneInfo("US/Pacific"))

print(UTC.isoformat())
print(eastern.isoformat())
print(pacific.isoformat())

# 2012-11-10T09:00:00+00:00
# 2012-11-10T04:00:00-05:00
# 2012-11-10T04:00:00-08:00

Also note this section from the docs:

The zoneinfo module does not directly provide time zone data, and instead pulls time zone information from the system time zone database or the first-party PyPI package tzdata, if available.

So don't forget to call a pip install tzdata, on Windows at least.

Answered by: Oliver843 | Posted: 06-11-2021



Similar questions

datetime - Python time to age, part 2: timezones

This question already has answers here:


datetime - How do I parse timezones with UTC offsets in Python?

Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this: datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".


python - django, datetime and timezones

I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red. My issue is that I have some users in different timezones than me saying that the events are ending at the wrong time. They should end at midnight on the day they are due. I have th...


Only some timezones working in datetime module for python

I'm trying to convert a time (including timezone) to just a time with everything in UTC. When i have the timezone GMT it works fine, but soon as i use PDT or PST i get an error. Am i going about this the right way or is there a better way to do this? >>> datetime.datetime.strptime("10:54:02 PM GMT", "%I:%M:%S %p %Z").strftime('%H:%M:%S') '22:54:02' I've seen pytz might be helpful ...


python - How to convert a datetime object between CEST and UTC timezones

I don't want to use the pytz library as the project I am working on requires paperwork to introduce dependencies. If I can achieve this without a third party library I'll be happier. I'm having trouble converting a date between CET and UTC when the date is in daylight savings. It's an hour different to what I expect: >>> print from_cet_to_utc(year=2017, month=7, day=24, hour=10...


python - Why are these datetime objects timezones not equal?

I'm having a problem with datetime objects. Here's my code: import datetime import pytz userInfo = 'Europe/Istanbul' # Current date, 2020-9-8 15:00 cd = datetime.datetime.now(pytz.timezone(userInfo)) # Example date, 2020-9-8 15:00 ed = datetime.datetime(2020, 9, 8, 15, 0, pytz.timezone(userInfo)) # Print both dates print('Example', ed, '\n', 'Current', cd, '\n') if ed == cd: print('Equa...


python - Datetime Timezones from String

I am trying to figure out how to make a datetime object aware through using a variable. I grab the timezone of the user and pass it through a form to be used. I have tried both of the below methods and am not having much success timezone_variable = "Europe/London" new_datetime = datetime(int(date_year), int(date_month), int(date_day), ...


python - Display datetime local timezones

I am pretty new to this so not sure how it works, I have tried reading up but think I just need a straightforward explanation to what is probably a basic question. From an API I am getting a baseball schedule and the dates comes through as a datetime object like this '2021-04-15T02:10:00.000Z'. I know the Z means UTC time, but will it display in local time where ever the user is? If I save...


datetime - Python time to age, part 2: timezones

This question already has answers here:


datetime - How do I parse timezones with UTC offsets in Python?

Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this: datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".


python - django, datetime and timezones

I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red. My issue is that I have some users in different timezones than me saying that the events are ending at the wrong time. They should end at midnight on the day they are due. I have th...


python - Dealing with timezones in Django

I'm trying to deal with timezone information in Django. I tried doing something like: results = Competitor.objects.raw("SELECT official_start AT TIME ZONE 'UTC', official_finish AT TIME ZONE 'UTC' FROM competitor WHERE race_id=1") Thinking that this way I would know that the timezone was UTC but say I store a time in the database that is '2010-07-30 15:11:23' in UTC, in Django it will show...


python - Facebook Events and timezones, how to convert UTC datetime to what facebook expects?

My application needs to create facebook events. Everything works fine, but I can't get the timezones correct. The start/end dates are all wrong. Facebook's Event API docs say this: Note: The start_time and end_time are the times that were input by the event creator, converted to UTC after assuming that they were in Pacific time (Daylight Savings or Standard, depending on the date of the event), then ...


Dealing with timezones for sending sms -python /django

I need to send sms globally to different timezones to each customer registered online The messages are scheduled to be send each month. I have the country details of each cutomer . I would be writing a python script and add it to cronjobs for sending sms. The issue I am facing is knowing a safe time ( sometime during the day) based on the country for sending the SMS. MY server runs in Australian/Melbourne timezone.What i...


python - Django 1.4 and timezones

In django docs, it is written that they can always store the datetime objects in TIME_ZONE provided in settings. I wanted to ask that is it just sufficient to date time aware objects or do we have to convert them to TIME_ZONE setting? ie if my TIME_ZONE = "America/Los_Angeles" and USE_TZ = True, and I try to save a time zone aware object which is in "UTC", will that work? That is, will django convert that "UTC" tim...


python - Timezones in Django 1.4 being returned in UTC from DB

Here are my two relevant settings in settings.py for my django project. USE_TZ = True TIME_ZONE = 'Europe/Stockholm' I have a DateTimeField defined like this in models. triggeredTime = models.DateTimeField('Utlöses') This is managed by the Django admin app and a form. So the form allows me to enter a date and time into this field of the database. The DB ...


python - how to convert database dates to strings with timezones

I have the following line of code datetime.datetime.strftime(expire_date, "%m/%d/%Y %H:%M %p %Z") but it is not outputting the date with the timezone. How can I change it so that it does?


Elegant way to adjust date timezones in Python

I'm based in the UK, and grappling with summer time BST and timezones. Here's my code: TIME_OFFSET = 1 # 0 for GMT, 1 for BST def RFC3339_to_localHHMM(input): # Take an XML date (2013-04-08T22:35:00Z) # return e.g. 08/04 23:35 return (datetime.datetime.strptime(input, '%Y-%m-%dT%H:%M:%SZ') + datetime.timedelta(hours=TIME_OFFSET)).strftime('%d/%m %H...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top