Last active
February 13, 2018 14:09
-
-
Save yassineAlouini/87c167869c654c5b2f2977c1ad6865ac to your computer and use it in GitHub Desktop.
Localize a timestamp column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytz | |
import pandas as pd | |
def localize_datetime(input_df, timezone='Europe/Paris', | |
datetime_column='tms_gmt'): | |
""" | |
Convert datetime column from UTC to another timezone. | |
""" | |
tmz = pytz.timezone(timezone) | |
df = input_df.copy() | |
return (df.set_index(datetime_column) | |
.tz_localize(pytz.utc) # UTC time | |
.tz_convert(tmz) # Timezone time | |
.reset_index()) | |
def delocalize_datetime(input_df, timezone='Europe/Paris', | |
datetime_column='tms'): | |
""" | |
Convert datetime column from a timezone to UTC. | |
""" | |
tmz = pytz.timezone(timezone) | |
df = input_df.copy() | |
return (df.set_index(datetime_column) | |
.tz_localize(tmz, ambiguous=True) # Timezone time | |
.tz_convert(pytz.utc) # UTC time | |
.reset_index()) | |
DATA_PATH = 'path/to/csv' | |
TIMEZONE = 'your/timezone' | |
df = (pd.read_csv(DATA_PATH) | |
.assign(tms=lambda df: pd.to_datetime(df.tms_gmt)) | |
.pipe(localize_datetime, datetime_column='tms', timezone=TIMEZONE) | |
.drop('tms_gmt', axis=1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment