Python: convert 'days since 1990' to datetime object

前端 未结 3 1638
长情又很酷
长情又很酷 2021-02-20 02:04

I have a time series that I have pulled from a netCDF file and I\'m trying to convert them to a datetime format. The format of the time series is in \'days since 1990-01-01 00:0

3条回答
  •  清歌不尽
    2021-02-20 02:35

    We can do this in a couple steps. First, we are going to use the dateutil library to handle our work. It will make some of this easier.

    The first step is to get a datetime object from your string (1990-01-01 00:00:00 +10). We'll do that with the following code:

    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    import dateutil.parser
    
    days_since = '1990-01-01 00:00:00 +10'
    days_since_dt = dateutil.parser.parse(days_since)
    

    Now, our days_since_dt will look like this:

    datetime.datetime(1990, 1, 1, 0, 0, tzinfo=tzoffset(None, 36000))
    

    We'll use that in our next step, of determining the new date. We'll use relativedelta in dateutils to handle this math.

    new_date = days_since_dt + relativedelta(days=9465.0)
    

    This will result in your value in new_date having a value of:

    datetime.datetime(2015, 12, 1, 0, 0, tzinfo=tzoffset(None, 36000))
    

    This method ensures that the answer you receive continues to be in GMT+10.

提交回复
热议问题