Search code examples
pythondatetimeleap-year

Leap year convention in python datetime


I'm reading data in which the time variable was encoded with udunits. This means that the time variable is hours since 1-1-1 00:00:00, however, it does not follow standard leap year conventions.

I'm trying to convert the hours since 1-1-1 00:00:00 to a python datetime object but end up with the incorrect answer because datetime does follow leap year convention. For example:

t_data = 17584272    # This is time stamp for January 1st, 2007 in the data file
day = datetime.datetime(1,1,1) + datetime.timedelta(hours=t_data)
print(day)

Result:

>>> 2007-01-03 00:00:00

Is there a way to 'turnoff' leap year convention in python datetime?

Thanks in advance for your help!


Solution

  • I think you're incorrect in your assessment that leap years aren't being used properly, all of the samples you've listed are consistent. There's just some offset that you need to account for. It's not necessary to know what the offset is, you just start with a known date and hour figure.

    def udtimestamp(hours):
        return datetime.datetime(1990,1,1) + datetime.timedelta(hours=hours-17435256)
    
    >>> for x in (17584272,1.7435256E7,1.747908E7,1.7522904E7,1.763688E7):
        print udtimestamp(x)
    
    2007-01-01 00:00:00
    1990-01-01 00:00:00
    1995-01-01 00:00:00
    2000-01-01 00:00:00
    2013-01-01 00:00:00