Skip to content Skip to sidebar Skip to footer

Python Pandas Timestamps To Local Time String With Daylight Saving

I have a dataframe with a TimeStamps column. I want to convert it to strings of local time, ie with daylight saving. So I want to convert ts[0] below to '2015-03-30 03:55:05'. Pan

Solution 1:

DST is relative to your location (e.g. London DST began a few weeks after NY). You first need to make the timestamp timezone aware:

from pytz import UTC
from pytz import timezone
import datetime as dt

ts = pd.Timestamp(datetime.datetime(2015, 3, 31, 15, 47, 25, 901597))
# or...
ts = pd.Timestamp('2015-03-31 15:47:25.901597')
# ts is a Timestamp, but it has no idea where in the world it is...>>> ts.tzinfo isNoneTrue# So the timestamp needs to be localized.  Assuming it was originally a UTC timestamp, it can be localized to UTC.
ts_utc = ts.tz_localize(UTC)
# Once localized, it can be expressed in other timezone regions, e.g.: 
eastern = pytz.timezone('US/Eastern')
ts_eastern = ts_utc.astimezone(eastern)
# And to convert it to an ISO string of local time (e.g. eastern):>>> ts_eastern.isoformat()
'2015-03-30T08:09:27.143173-04:00'

See pytz or datetime for more information.

Post a Comment for "Python Pandas Timestamps To Local Time String With Daylight Saving"