Skip to content

Commit

Permalink
Add an optional timezone argument to m.u.iso8601.totimestamp().
Browse files Browse the repository at this point in the history
See #104.

Release as 0.3.24.
  • Loading branch information
nmlorg committed Jul 19, 2024
1 parent d0110b6 commit a7a1c5b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
22 changes: 16 additions & 6 deletions metabot/util/iso8601.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import datetime
import re

import pytz

def totimestamp(isoformat):

def totimestamp(isoformat, timezone=None):
"""Convert a string like YYYY-MM-DDTHH:MM:SS+HH:MM to the number of seconds since 1970-01-01."""

year, month, day, _, hour, minute, second, fraction, _, utchour, utcminute = re.match(
year, month, day, _, hour, minute, second, fraction, offset, utchour, utcminute = re.match(
r'(\d{4})-?(\d{1,2})-?(\d{1,2})'
r'(T(\d{1,2}):?(\d{1,2}):?(\d{1,2})'
r'([.]\d+)?'
Expand All @@ -17,9 +19,13 @@ def totimestamp(isoformat):
int(second or 0), int(1000000 * float(fraction or 0)))
if utchour and utcminute:
tzinfo = _TimeZone(int(utchour) + float(utcminute) / 60)
elif offset == 'Z':
tzinfo = pytz.utc
elif timezone:
tzinfo = pytz.timezone(timezone)
else:
tzinfo = _UTC
return (dtime.replace(tzinfo=tzinfo) - _EPOCH).total_seconds()
tzinfo = pytz.utc
return (tzinfo.localize(dtime) - _EPOCH).total_seconds()


class _TimeZone(datetime.tzinfo):
Expand All @@ -40,6 +46,10 @@ def utcoffset(self, unused_dt):
def dst(unused_dt): # pragma: no cover pylint: disable=arguments-differ
return datetime.timedelta(0)

def localize(self, dt):
"""See https://pypi.org/project/pytz/#example-usage."""

return dt.replace(tzinfo=self)


_UTC = _TimeZone(0)
_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=_UTC)
_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = 'metabot'
version = '0.3.23.1'
version = '0.3.24'
description = 'Modularized, multi-account bot.'
readme = 'README.md'
authors = [
Expand Down

0 comments on commit a7a1c5b

Please sign in to comment.