def mjd_to_greg(mjd): """ Convert MJD into gregorian date. Parameters ---------- mjd : float Date in the format MJD. Returns ---------- greg : string Gregorian date (format: YYYYMMDD_HHMMSS) Examples ---------- >>> mjd = greg_to_mjd('19881103_000000') >>> greg = mjd_to_greg(mjd) >>> print('MJD={} ->'.format(round(mjd, 2)), 'GREG={}'.format(greg)) MJD=47468.0 -> GREG=19881103_000000 """ year, month, day, fracday, baddate = slalib.sla_djcl(mjd) if baddate: raise ValueError(BadMJD) sign, (hour, minute, second, frac) = slalib.sla_dd2tf(2, fracday) s = '{:4d}{:2d}{:2d}_{:2d}{:2d}{:2d}'.format(year, month, day, hour, minute, second) s = s.replace(' ', '0') return s
def getDate(self, line, columns): if columns['sep'] == ',': fields = line.split(columns['sep']) dateStr = fields[columns['Date']['num']].strip() else: dateStr = line[columns['Date']['start']:columns['Date']['end']] if columns['Date']['type'] == 'CAL': dateFmt = columns['Date']['format'] if '.' in dateStr: dateTimeStr, msecStr = dateStr.split('.') msec = int(msecStr) else: dateTimeStr = dateStr msec = 0 elif columns['Date']['type'] == 'JD': # The subtraction is because sla_djcl wants an MJD jd = float(dateStr) yy, mm, dd, fracDay, j = slalib.sla_djcl(jd - 2400000.5) sign, hmsf = slalib.sla_dd2tf(3, fracDay) dateStr = '-'.join([str(yy), '%02d' % mm, '%02d' % dd]) timeStr = ':'.join( ['%02d' % hmsf[0], '%02d' % hmsf[1], '%02d' % hmsf[2]]) dateTimeStr = ' '.join([dateStr, timeStr]) dateFmt = '%Y-%m-%d %H:%M:%S' msec = int(hmsf[3]) date = datetime.datetime.strptime( dateTimeStr, dateFmt) + datetime.timedelta(milliseconds=msec) return date
def mjd_utc2datetime(mjd): """Converts a passed Modified Julian date to a Python datetime object. 'None' is returned if the conversion was not possible.""" year, month, day, frac, status = S.sla_djcl(mjd) if status != 0: return None sign, hms = S.sla_dd2tf(0, frac) dt = datetime(year, month, day, hms[0], hms[1], hms[2]) return dt
def jd_utc2datetime(jd): """Converts a passed Julian date to a Python datetime object. 'None' is returned if the conversion was not possible.""" try: mjd_utc = jd - 2400000.5 except TypeError: try: mjd_utc = float(jd) - 2400000.5 except: return None year, month, day, frac, status = S.sla_djcl(mjd_utc) if status != 0: return None sign, hms = S.sla_dd2tf(0, frac) dt = datetime(year, month, day, hms[0], hms[1], hms[2]) return dt
def processDatetime(dateTime): """ Returns a Python datetime object. Given a date/time, supplied as any any of the following: - Python datetime object - Julian date (JD) - Modified Julian date (MJD) - YYYYMMDD.DDDD - YYYYMMDD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that) - YYYY-MM-DD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that) - YYYY/MM/DD HH:MM:SS (You can leave off the HH:MM:SS or some subset of that) - YYYY-MMM-DD HH:MM returns the equivalent date/time, expressed as a Python datetime object. Args: jd: The date/time Returns: The date/time, expressed as a datetime object """ dateTimeFormats = ('%Y%m%d', '%Y-%m-%d', '%Y/%m/%d', '%Y%m%d %H', '%Y%m%d %H%M', '%Y%m%d %H%M%S', '%Y%m%d %H', '%Y%m%d %H:%M', '%Y%m%d %H:%M:%S', '%Y%m%d-%H', '%Y%m%d-%H:%M', '%Y%m%d-%H:%M:%S', '%Y-%m-%dT%H', '%Y-%m-%dT%H:%M', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H', '%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H', '%Y/%m/%d %H:%M', '%Y/%m/%d %H:%M:%S', '%Y-%b-%d %H:%M') # if the input value is already a datetime object, just return it. if isinstance(dateTime, datetime.datetime): return dateTime else: # The input value might be a JD, MJD, or a YYYYMMDD.DDDD. If # it is any of those, we can convert it to a float. If we # can't convert it to a float, it must be one of the string # representations, e.g., YYYYMMDD HH:MM:SS. try: dateTime = float(dateTime) except ValueError: pass if isinstance(dateTime, float): # The input is a float. Now we have to determine if it is # YYYYMMDD.DDDD or JD/MJD. If the string represention of # the date portion of the input is the same length as # 'YYYYMMDD', it must be a YYYYMMDD.DDDD. JD and MJD dates # are typically either 7 or 5 characters long, # respectively, not 8 characters, at least for the range # of dates that we usually care about. (fracDay, date) = math.modf(dateTime) if len(str(int(date))) == len('YYYYMMDD'): # Convert input YYYYMMDD.DDDD into datetime object return datetime.datetime.strptime(str( int(date)), '%Y%m%d') + datetime.timedelta(days=fracDay) else: # Input is either JD or MJD. Raise an exception if we # slalib isn't available. if not jdOk: raise NoSlalibError( 'Julian dates require slalib, but slalib is not available' ) # For the dates that we care about, if the value is # greater than 2400000, we assume that it is a JD, so # convert it to an MJD. if dateTime > 2400000: dateTime -= 2400000.5 yy, mm, dd, fracDay, j = slalib.sla_djcl(dateTime - 2400000.5) sign, hmsf = slalib.sla_dd2tf(3, fracDay) dateStr = '-'.join([str(yy), '%02d' % mm, '%02d' % dd]) timeStr = ':'.join( ['%02d' % hmsf[0], '%02d' % hmsf[1], '%02d' % hmsf[2]]) dateTimeStr = ' '.join([dateStr, timeStr]) dateFmt = '%Y-%m-%d %H:%M:%S' msec = int(hmsf[3]) return datetime.datetime.strptime( dateTimeStr, dateFmt) + datetime.timedelta(milliseconds=msec) elif isinstance(dateTime, str): # The input date is a string. Using one of the acceptable # formats, parse it and create a datetime object. dateTimeObj = None for format in dateTimeFormats: try: dateTimeObj = datetime.datetime.strptime(dateTime, format) break except ValueError: pass # If we were able to parse the input string, return the # datetime object. Otherwise, raise an exception. if dateTimeObj: return dateTimeObj else: raise DateTimeFormatError('Unexpected date/time format: %s' % dateTime) else: raise DateTimeFormatError('Unexpected date/time format: %s' % dateTime)