lair.clock.convert_timezones#
- lair.clock.convert_timezones(x, totz, fromtz=None, localize=False, driver=None, ambiguous='raise', nonexistent='raise')[source]#
Convert the times from one timezone to another.
- Parameters:
x (dt.datetime | pd.Timestamp | list[dt.datetime] | pd.DataFrame | pd.Series) – The times to convert. With
driver='pandas', the index of a DataFrame or the values of a Series. Without it, a single time or a list (or other iterable) of them.totz (str) – The timezone to convert the times to.
fromtz (str, optional) – The timezone of the naive input times. Required if any input time is naive (tz-aware times are converted from their own timezone).
localize (bool, optional) – If True, the times will be localized to the totz timezone, by default False
driver (None | 'pandas', optional) – None for a list of datetimes, ‘pandas’ for a DataFrame or Series.
ambiguous ('raise' | 'NaT' | 'infer' | bool | array of bool, optional) – How to localize naive times that happen twice in
fromtz(DST fall-back), with pandastz_localizesemantics: True is the DST (first) instant, False the standard-time (second) one, ‘NaT’ gives NaT, and ‘raise’ (the default) raises a ValueError. An array gives one flag per input time (for a list, aware elements’ flags are ignored).nonexistent ('raise' | 'NaT' | 'shift_forward' | 'shift_backward' | timedelta, optional) – How to localize naive times that don’t exist in
fromtz(DST spring-forward), with pandastz_localizesemantics. Default ‘raise’.
- Returns:
dt.datetime | pd.Timestamp | list[dt.datetime] | pd.DataFrame | pd.Series – The converted times, in the shape of
x. A single time gives a single time, converted the way each element of a list is: adatetimestays adatetimeand apd.Timestampstays apd.Timestamp(pd.NaTifambiguousornonexistentis'NaT'and the time is one of those).- Raises:
ValueError – If there are naive times and no
fromtz, or a naive time is ambiguous or nonexistent infromtzandambiguous/nonexistentis ‘raise’, ordriver='pandas'andxis not a DataFrame or Series.
See also
Examples
18:00 UTC in January is 11:00 in Salt Lake City:
>>> import datetime as dt >>> from lair.clock import convert_timezones >>> convert_timezones(dt.datetime(2024, 1, 15, 18), "America/Denver", fromtz="UTC") datetime.datetime(2024, 1, 15, 11, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Denver'))
A list gives a list, converted time by time:
>>> convert_timezones( ... [dt.datetime(2024, 1, 15, 18)], "America/Denver", fromtz="UTC" ... ) [datetime.datetime(2024, 1, 15, 11, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Denver'))]
The index of a DataFrame, kept naive in local time with
localize=True:>>> import pandas as pd >>> data = pd.DataFrame( ... {"ch4": [2000.0]}, index=pd.to_datetime(["2024-07-15 18:00"]) ... ) >>> convert_timezones( ... data, "America/Denver", fromtz="UTC", localize=True, driver="pandas" ... ) ch4 2024-07-15 12:00:00 2000.0