Search code examples
pythonmatlabdatetimepython-datetime

Converting a day decimal number array to unix timestamp in Python


I have an array of numbers (e.g 279.341, 279.345, 279.348) which relate to the date and time in 2017 (its supposed to be October 6th 2017). To be able to compare this data to another dataset I need to convert that array into an array of UNIX timestamps.

I have successfully done something similar in matlab (code below) but don't know how to translate this to Python.

MatLab:

adcpTimeStr = datestr(adcp.adcp_day_num,'2017 mmm dd HH:MM:SS'); 
adcpTimeRaw = datetime(adcpTimeStr,'InputFormat','yyyy MMM dd HH:mm:ss');
adcpTimenumRaw = datenum(adcpTimeRaw)';

What would be a good way of converting the array into UNIX timestamps?


Solution

  • assuming these numbers are fractional days of the year (UTC) and the year is 2017, in Python you would do

    from datetime import datetime, timedelta, timezone
    
    year = datetime(2017,1,1, tzinfo=timezone.utc) # the starting point
    doy = [279.341, 279.345, 279.348]
    
    # add days to starting point as timedelta and call timestamp() method:
    unix_t = [(year+timedelta(d)).timestamp() for d in doy]
    # [1507363862.4, 1507364208.0, 1507364467.2]