Source code for irfpy.asperacommon.dd
''' DD module. DD is developed by CESR.
DD module provides some useful functions related to DD.
'''
import logging as _logging
_logger = _logging.getLogger(__name__)
import datetime
import string
import dateutil.parser
[docs]def ncdfdd2datetime(ddtime):
''' Convert DD time that is read from NCDF file to datetime instance.
When DD time is read from NCDF file, it is in numpy array with single char.
The equivalent time format can be made as follows.
>>> import numpy
>>> t = numpy.array(['2', '0', '0', '9', '3', '6', '4', '1', '9', '2', '4', '0', '2',
... '3', '6', '7', ''],
... dtype='|S1')
In this case, the datetime object can be get as follows.
>>> print(ncdfdd2datetime(t))
2009-12-31 19:24:02.367000
'''
dd = b''.join(ddtime).decode('latin-1')[:16]
return ddtime2datetime(dd)
[docs]def ddtime2datetime(ddtime):
r''' Convert DD time to datetime instance.
:param ddtime: DD time. 16 length string.
Note that the DD time's DOY starts from 0, i.e. January 1st is DD DOY=0.
>>> t0 = ddtime2datetime('2009000000000000')
>>> print(t0.strftime('%F'))
2009-01-01
>>> t0 = ddtime2datetime('2009001125308444')
>>> print(t0.strftime('%FT%T.%f'))
2009-01-02T12:53:08.444000
>>> t0 = ddtime2datetime('2008140123456789') # Check for leap year.
>>> print(t0.strftime('%FT%T.%f'))
2008-05-20T12:34:56.789000
>>> t0 = ddtime2datetime('2009140123456789')
>>> print(t0.strftime('%FT%T.%f'))
2009-05-21T12:34:56.789000
In DD's netcdf file, the returned value is ndarray instance.
Simplest way of converting is using :func:`ncdfdd2datetime`.
If the length is >16, the first 16 characters are only used.
If shorter input comes, ``None`` is returned.
>>> t0 = ddtime2datetime('')
>>> print(t0)
None
>>> t0 = ddtime2datetime('2009141133')
>>> print(t0)
None
>>> t0 = ddtime2datetime('20XX140123456790')
>>> print(t0)
None
'''
# if not isinstance(ddtime, str):
# raise TypeError('DD time instance is not str (but is *%s*)' % ddtime.__class__.__name__)
ddtime = str(ddtime)
if len(ddtime) < 16:
_logger.warning('Wrong input string format: "{}". Length is {} but should be 16.'.format(ddtime, len(ddtime)))
return None
try:
year = int(ddtime[0:4])
doi = int(ddtime[4:7]) # Not exactly DOI. Offset of 1.
hr = int(ddtime[7:9])
mn = int(ddtime[9:11])
se = int(ddtime[11:13])
sub = int(ddtime[13:16])
except ValueError:
return None
firstdayofyear = datetime.datetime(year, 1, 1, hr, mn, se, sub*1000)
doioffset = datetime.timedelta(days=doi) # Jan 1 is 0 in this case, so this is ok.
return firstdayofyear + doioffset