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)
| 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: |