MCPcopy Index your code
hub / github.com/python-pendulum/pendulum / convert

Method convert

src/pendulum/tz/timezone.py:76–139  ·  view source on GitHub ↗

Converts a datetime in the current timezone. If the datetime is naive, it will be normalized. >>> from datetime import datetime >>> from pendulum import timezone >>> paris = timezone('Europe/Paris') >>> dt = datetime(2013, 3, 31, 2, 30, fold=1)

(self, dt: _DT, raise_on_unknown_times: bool = False)

Source from the content-addressed store, hash-verified

74 return self.key
75
76 def convert(self, dt: _DT, raise_on_unknown_times: bool = False) -> _DT:
77 """
78 Converts a datetime in the current timezone.
79
80 If the datetime is naive, it will be normalized.
81
82 >>> from datetime import datetime
83 >>> from pendulum import timezone
84 >>> paris = timezone('Europe/Paris')
85 >>> dt = datetime(2013, 3, 31, 2, 30, fold=1)
86 >>> in_paris = paris.convert(dt)
87 >>> in_paris.isoformat()
88 '2013-03-31T03:30:00+02:00'
89
90 If the datetime is aware, it will be properly converted.
91
92 >>> new_york = timezone('America/New_York')
93 >>> in_new_york = new_york.convert(in_paris)
94 >>> in_new_york.isoformat()
95 '2013-03-30T21:30:00-04:00'
96 """
97
98 if dt.tzinfo is None:
99 # Technically, utcoffset() can return None, but none of the zone information
100 # in tzdata sets _tti_before to None. This can be checked with the following
101 # code:
102 #
103 # >>> import zoneinfo
104 # >>> from zoneinfo._zoneinfo import ZoneInfo
105 #
106 # >>> for tzname in zoneinfo.available_timezones():
107 # >>> if ZoneInfo(tzname)._tti_before is None:
108 # >>> print(tzname)
109
110 offset_before = cast(
111 "_datetime.timedelta",
112 (self.utcoffset(dt.replace(fold=0)) if dt.fold else self.utcoffset(dt)),
113 )
114 offset_after = cast(
115 "_datetime.timedelta",
116 (self.utcoffset(dt) if dt.fold else self.utcoffset(dt.replace(fold=1))),
117 )
118
119 if offset_after > offset_before:
120 # Skipped time
121 if raise_on_unknown_times:
122 raise NonExistingTime(dt)
123
124 dt = cast(
125 "_DT",
126 dt
127 + (
128 (offset_after - offset_before)
129 if dt.fold
130 else (offset_before - offset_after)
131 ),
132 )
133 elif offset_before > offset_after and raise_on_unknown_times:

Callers 15

datetimeMethod · 0.95
createMethod · 0.45
in_timezoneMethod · 0.45
addMethod · 0.45
dtFunction · 0.45
test_setting_timezoneFunction · 0.45
test_basic_convertFunction · 0.45
test_repeated_timeFunction · 0.45

Calls 5

NonExistingTimeClass · 0.90
AmbiguousTimeClass · 0.90
utcoffsetMethod · 0.80
astimezoneMethod · 0.80
replaceMethod · 0.45

Tested by 15

dtFunction · 0.36
test_setting_timezoneFunction · 0.36
test_basic_convertFunction · 0.36
test_repeated_timeFunction · 0.36
test_on_last_transitionFunction · 0.36