Skip to content

Commit

Permalink
Support for tz-aware datetime.datetime objects
Browse files Browse the repository at this point in the history
## Original issue ##
Issue: python-telegram-bot#1409 
version: 12.0.0b1

## Changes ##
The `._put()` method can now accept utc_offset-aware/timezone-aware `datetime.datetime` objects. This helps bots to be hosted on a server with any timezone without complications.

To convert datetimes to UTC, a "UTC" subclass of the `datetime.tzinfo` class was added, and used in `._put()`.

## Other options considered ##
- Changing all the `.now()` comparisons in `._put()` to `.utcnow()`. This was not chosen, since it would cause a major compatibility issue. Bots would have to be rewritten to pass in UTC datetimes, instead of local (computer time) datetimes, into the jobqueue.run_once and other methods. This would likely be unwanted behaivour.
  • Loading branch information
torresjrjr committed Jul 20, 2019
1 parent 984bea1 commit dfc835f
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion telegram/ext/jobqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,22 @@ class Days(object):
EVERY_DAY = tuple(range(7))


class UTC(datetime.tzinfo):
"""UTC"""

ZERO = datetime.timedelta(0)
HOUR = datetime.timedelta(hours=1)

def utcoffset(self, dt):
return ZERO

def tzname(self, dt):
return "UTC"

def dst(self, dt):
return ZERO


class JobQueue(object):
"""This class allows you to periodically perform tasks with the bot.
Expand Down Expand Up @@ -77,7 +93,11 @@ def _put(self, job, next_t=None, last_t=None):
raise ValueError('next_t is None')

if isinstance(next_t, datetime.datetime):
next_t = (next_t - datetime.datetime.now()).total_seconds()
if next_t.tzinfo == None:
next_t = (next_t - datetime.datetime.now()).total_seconds()
else:
next_t = next_t.astimezone(UTC()).replace(tzinfo=None)
next_t = (next_t - datetime.datetime.utcnow()).total_seconds()

elif isinstance(next_t, datetime.time):
next_datetime = datetime.datetime.combine(datetime.date.today(), next_t)
Expand Down

0 comments on commit dfc835f

Please sign in to comment.