22
33import re
44
5- import pendulum
6- from pendulum .datetime import DateTime
5+ from whenever import Instant , ZonedDateTime
76
87REGEX_MAPPING = {
98 "seconds" : r"(\d+)(s|sec|second|seconds)" ,
@@ -16,47 +15,58 @@ class TimestampFormatError(ValueError): ...
1615
1716
1817class Timestamp :
19- def __init__ (self , value : str | DateTime | Timestamp | None = None ):
20- if value and isinstance (value , DateTime ):
18+ obj : ZonedDateTime
19+
20+ def __init__ (self , value : str | ZonedDateTime | Timestamp | None = None ):
21+ if value and isinstance (value , ZonedDateTime ):
2122 self .obj = value
2223 elif value and isinstance (value , self .__class__ ):
2324 self .obj = value .obj
2425 elif isinstance (value , str ):
2526 self .obj = self ._parse_string (value )
2627 else :
27- self .obj = DateTime .now (tz = "UTC" )
28+ self .obj = ZonedDateTime .now ("UTC" )
2829
2930 @classmethod
30- def _parse_string (cls , value : str ) -> DateTime :
31+ def _parse_string (cls , value : str ) -> ZonedDateTime :
3132 try :
32- parsed_date = pendulum . parse (value )
33- if isinstance (parsed_date , DateTime ):
33+ parsed_date = ZonedDateTime . parse_common_iso (value )
34+ if isinstance (parsed_date , ZonedDateTime ):
3435 return parsed_date
35- except (pendulum .parsing .exceptions .ParserError , ValueError ):
36+ except ValueError :
37+ pass
38+
39+ try :
40+ parsed_date_instant = Instant .parse_common_iso (value )
41+ if isinstance (parsed_date_instant , Instant ):
42+ return parsed_date_instant .to_tz ("UTC" )
43+ except ValueError :
3644 pass
3745
38- params = {}
46+ params : dict [ str , float ] = {}
3947 for key , regex in REGEX_MAPPING .items ():
4048 match = re .search (regex , value )
4149 if match :
42- params [key ] = int (match .group (1 ))
50+ params [key ] = float (match .group (1 ))
4351
4452 if not params :
4553 raise TimestampFormatError (f"Invalid time format for { value } " )
4654
47- return DateTime .now (tz = "UTC" ).subtract (** params )
55+ return ZonedDateTime .now ("UTC" ).subtract (** params ) # type: ignore[call-overload]
4856
4957 def __repr__ (self ) -> str :
5058 return f"Timestamp: { self .to_string ()} "
5159
5260 def to_string (self , with_z : bool = True ) -> str :
53- iso8601_string = self .obj .to_iso8601_string ()
54- if not with_z and iso8601_string [- 1 ] == "Z" :
61+ if with_z :
62+ return self .obj .instant ().format_common_iso ()
63+ iso8601_string = self .obj .format_common_iso ()
64+ if iso8601_string [- 1 ] == "Z" :
5565 iso8601_string = iso8601_string [:- 1 ] + "+00:00"
5666 return iso8601_string
5767
5868 def to_timestamp (self ) -> int :
59- return self .obj .int_timestamp
69+ return self .obj .timestamp ()
6070
6171 def __eq__ (self , other : object ) -> bool :
6272 if not isinstance (other , Timestamp ):
0 commit comments