0

I am working on a crypto bot and using the datetime module to send price updates via SMS.

from datetime import datetime
current_time = datetime.now()

The datetime module is in military time (24 hour clock) and 7 hours ahead of my local time (PST), and I convert it by subtracting 7 from the time:

pst = abs(int(current_time.hour) - 7)

If the time is between 1 AM - 11 AM PST this works perfectly.
If the time is between 12 PM - 4 PM, I do:

if pst > 12 or pst == 0:
    pst_time = abs(pst) - 12

5 PM - 12 AM PST doesn't work as current_time = resets 0 to 7 and are < 12 which won't trigger the if statement.

Any advice on how to cleanly fix this without creating a huge table of numbers and setting them to a specific hour?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • why don't you use another module, like `pytz` or `zoneinfo`? – rv.kvetch Aug 16 '22 at 01:20
  • Does this answer your question? [Display the time in a different time zone](https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone) – FObersteiner Aug 16 '22 at 05:42

1 Answers1

0

In Python 3.9+, you can use the builtin zoneinfo module:

>>> from zoneinfo import available_timezones
>>> available_timezones()

If you see an empty set() as the output, you might need to install tzdata package:

pip install tzdata

Sample usage with datetime module:

from datetime import datetime
from zoneinfo import ZoneInfo

PST = ZoneInfo('US/Pacific')

dt = datetime(2020, 10, 31, 12, tzinfo=PST)
print(dt)  # 2020-10-31 12:00:00-07:00
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53