0

I'm trying to create HTTP endpoints:

  1. one that returns posts to a user that were created in a given month in the requestor's time zone.
  2. 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

  1. What is the format or string representation "US/Pacific" called ?
  2. How can I convert the string formats "PST", "UCT" or "CST" to their respective formats like "US/Pacific", etc. in Python ?
  3. What's the name for this format like "US/Pacific" ?
  4. Is there a sort of dictionary that maps "PST" to "US/Pacific" ?
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Could you provide datasample for such timestamp coming from the API? – jlandercy Dec 23 '21 at 13:29
  • 1
    Don't forget Daylight Saving.... – jtlz2 Dec 23 '21 at 13:30
  • Also the problem you are facing might be related to Summer Time shift. PST is a short name for Pacific Time with Summer Time active while US/Pacific is not restricted to ST and will take account of ST when needed (at least in python). – jlandercy Dec 23 '21 at 13:33
  • @jlandercy sure. It'd be something like `month=1`, `year=2021` and `time_zone='PST'` –  Dec 23 '21 at 13:35
  • @jlandercy didn't know that. That's very nice. –  Dec 23 '21 at 13:37

2 Answers2

4

Time zone terminology

How to define, represent or refer to a time zone? Some terms:

(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:

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:

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:

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:

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 1
    `timezone('PST')` gives `pytz.exceptions.UnknownTimeZoneError: 'PST'` –  Dec 23 '21 at 14:41
  • @user8714896 Thanks, did not test and expected the common abbreviation to be present. ️ Now it's tested + fixed ... and extended _terminology_ and new 3.9 module _zoneinfo_. – hc_dev Dec 23 '21 at 18:33
  • I was probably not explicit enough, I meant more like a string "PST" to "US/Pacific" not necessarily a timezone subclass –  Dec 24 '21 at 02:18
  • the problem with abbreviated tz names like "PST" is that at least some of them are ambiguous (e.g. search for "BST" ;-)) - That's why they're not supported by libraries such as pytz. A common way to remove that ambiguity is to define a mapping dict; e.g. mapping "PST" to "America/Los_Angeles". `dateutil`s [parser](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse) can be fed with such a mapping for example. – FObersteiner Dec 26 '21 at 12:52
0
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

  1. Show date-time for different timezone/country
  2. Timezone Conversion
  3. Timezone unaware/naive to Timezone aware
  4. Issue with replace
Amrit Prasad
  • 373
  • 6
  • 18