Converting between datetime, Timestamp and datetime64

前端 未结 12 1450
傲寒
傲寒 2020-11-22 01:43

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)?

In the following code, I create a datetime,

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 02:14

    If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime().

    pd.date_range('20110101','20110102',freq='H').to_pydatetime()
    
    > [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
       datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
       ....
    

    It also supports timezones:

    pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()
    
    [ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=)
     datetime.datetime(2011, 1, 1, 12, 0, tzinfo=)
    ....
    

    NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime() on the entire series. You will need to call .to_pydatetime() on each individual datetime64 using a list comprehension or something similar:

    datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]
    

提交回复
热议问题