I'm trying to create an endpoint that returns post to a user that were created in a given month in the requestor's time zone. Unfortunately Pyzt the library I'm using for getting all posts from a month only accepts time zone in the format "US/Pacific" (Whatever format this is please tell me). I have another endpoint that gets the months possible for post. 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.
Question:
I'm trying to figure out a way to convert "UCT", "PST" and "CST"(I'd love it if someone told what format this is called) in string format to their respect formats in "US/Pacific"(Also what format is this called) also in string format in Python. Is there a way to do this? I'm guessing some sort of dictionary out there in the world that maps "PST" format to "US/Pacific."
CodePudding user response:
These 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:
from pytz import timezone
utc_time = datetime.datetime.utcnow()
tz = timezone('US/Pacific')
utc_time.replace(tzinfo=pytz.utc).astimezone(tz)
Note:
- the time-zone
tz
is built using pytz'stzinfo
API, e.g. withtimezone('PST')
ortimezone('US/Eastern')
- the
.replace()
is optional and resets the time zone of given date-time to default UTC.
See also:
CodePudding user response:
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