Skip to content

Commit

Permalink
Add support for timezone aware datetime as argument to `TOTP.timecode…
Browse files Browse the repository at this point in the history
…()` (pyauth#107)
  • Loading branch information
b4stien authored Sep 19, 2020
1 parent dc37ffe commit 9ff40e7
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/pyotp/totp.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Any, Union, Optional

import calendar
import datetime
import time

Expand Down Expand Up @@ -79,6 +80,16 @@ def provisioning_uri(self, name: Optional[str] = None, issuer_name: Optional[str
algorithm=self.digest().name,
digits=self.digits, period=self.interval)


def timecode(self, for_time: datetime.datetime) -> int:
i = time.mktime(for_time.timetuple())
"""
Accepts either a timezone naive (`for_time.tzinfo is None`) or
a timezone aware datetime as argument and returns the
corresponding counter value (timecode).
"""
if for_time.tzinfo:
i = calendar.timegm(for_time.utctimetuple())
else:
i = time.mktime(for_time.timetuple())
return int(i / self.interval)

0 comments on commit 9ff40e7

Please sign in to comment.