python pandas TimeStamps to local time string with daylight saving

前端 未结 1 1250
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 19:14

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-3

相关标签:
1条回答
  • 2021-01-13 20:11

    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 is None
    True
    
    # 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.

    0 讨论(0)
提交回复
热议问题