Fanning Software Consulting

Converting Date Strings to Seconds

Facebook Twitter RSS Google+

QUESTION: I have the date and the UTC time in two columns of my data file as [YYYYMMDD HRMISE], where YYYY is Year, MM is Month, DD is day, HR is Hours, MI is Minutes, and SE is Seconds. I need to convert this informaiton to the "time" variable according to NetCDF CF convention, which requires the time to be in seconds since 1970-01-01 00:00:00 (in UTC). Can you explain how to do this in IDL?

ANSWER: I would use the Julday function to do this. I would read the two columns of data as a single string array. Then, I would do something like this (using a scalar string as the example, but this will work just as well for a string array, too).

   str = '20131113 083122'
   year = Fix(StrMid(str,0,4))
   mon =  Fix(StrMid(str,4,2))
   day =  Fix(StrMid(str,6,2))
   hour = Fix(StrMid(str,9,2))
   min =  Fix(StrMid(str,11,2))
   sec =  Fix(StrMid(str,13,2))
   jultime = JulDay(mon,day,year,hour min,sec) - JulDay(1,1,1970,0,0,0)
   ncdfTime = jultime * 24 * 60 * 60
   Print, ncdfTime, Format='(F0.3)'

Note that this can also be accomplished using the “calendar format” specification in IDL.

   str = '20131113 083122'
   jd = 0d0
   ReadS, '20131113 083122', jd, FORMAT='(C(CYI4,CMOI2,CDI2,1x,CHI2,CMI2,CSI2))'
   jd -= Julday(1,1,1970,0,0,0)
   jd *= 86400d0
   ncdfTime = jd
   Print, ncdfTime, Format='(F0.3)'

In both cases, the value printed is 1384331482.000.

Converting CF-Compliant Seconds to a Date

To convert numbers in CF-compliant seconds back to a date, you simply reverse the process and use the CalDat function to do the conversion for you.

   julTime = ncdfTime / (24*60*60.0D) + JulDay(1,1,1970,0,0,0)
   CalDat, julTime, month, day, year, hour, min, sec
   Print, year, month, day, hour, min, sec

The results are shown here.

   2013          11          13           8          31       22.0000

Alternatively, you can use the "calendar" format from above to do the conversion for you.

   IDL> julTime = ncdfTime / (24*60*60.0D) + JulDay(1,1,1970,0,0,0)
   IDL> Print, String(julTime, FORMAT='(C(CYI4,CMOI2,CDI2,1x,CHI2,CMI2,CSI2))')
        20131113  83122

Version of IDL used to prepare this article: IDL 8.2.

Written: 12 November 2013