Localize naive UTC timestamps in pandas, then convert them to New York time
Quick Overview
Write a pandas function that treats tz-naive timestamps as UTC and returns them as time zone aware New York times, keeping the index and name. It tests the difference between localizing and converting time zones and how daylight saving offsets are applied.
Localize naive UTC timestamps in pandas, then convert them to New York time
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `def to_ny_time(s: pd.Series) -> pd.Series`. The input `s` is a tz-naive `datetime64[ns]` Series of UTC wall-clock times. Localize it to UTC with `s.dt.tz_localize('UTC')`, then convert it with `.dt.tz_convert('America/New_York')` and return the tz-aware Series.
The function must:
- Localize to UTC first, with no conversion at that step. Calling `tz_convert` on a naive Series raises.
- Return a Series with dtype `datetime64[ns, America/New_York]`, with daylight saving time handled automatically.
- Preserve the original index and `name`.
Example:
```text
naive 2021-01-01 12:00:00 (interpreted as UTC)
-> 2021-01-01 07:00:00-05:00 (America/New_York, EST)
```
Noon UTC on January 1 is 7:00 in New York, because New York is on Eastern Standard Time (UTC-5) in winter.
```hint What each step expects
Check what each method assumes about its input: one only accepts tz-naive values and the other only accepts tz-aware values.
```
### Constraints & Assumptions
- `s` is tz-naive with dtype `datetime64[ns]`.
- Every value is a UTC wall-clock time.
### What a Strong Answer Covers
- The difference between localizing (declaring which zone naive values are in) and converting (showing the same instants in another zone).
- Why the order matters and what goes wrong with the wrong order.
- The resulting dtype, and how each timestamp gets the EST or EDT offset that applies on its date.
- That the index and `name` carry through unchanged.
### Follow-up Questions
- How would you handle a Series that is already tz-aware?
- What about ambiguous or nonexistent local times during DST transitions?
- A downstream system cannot store time zones. How would you hand it New York wall-clock times?
Overview: Write a pandas function that treats tz-naive timestamps as UTC and returns them as time zone aware New York times, keeping the index and name. It tests the difference between localizing and converting time zones and how daylight saving offsets are applied.
Implement def to_ny_time(s: pd.Series) -> pd.Series. The input s is a tz-naive datetime64[ns] Series of UTC wall-clock times. Localize it to UTC with s.dt.tz_localize('UTC'), then convert it with .dt.tz_convert('America/New_York') and return the tz-aware Series.
The function must:
Localize to UTC first, with no conversion at that step. Calling
tz_convert
on a naive Series raises.
Return a Series with dtype
datetime64[ns, America/New_York]
, with daylight saving time handled automatically.