def fname2date(rinex_fname):
"""
Return the :class:`datetime` associated with the RIENX file
*rinex_fname* named according to the standard convention.
"""
basename = os.path.basename(rinex_fname)
doy = basename[4:7]
daily_or_hour = basename[7]
yy = basename[9:11]
dt = datetime.strptime(doy + yy, '%j%y')
if daily_or_hour == '0':
return dt
elif daily_or_hour in [chr(x) for x in range(ord('a'), ord('x') + 1)]:
return dt + timedelta(hours=ord(daily_or_hour) - ord('a'))
else:
raise ValueError('could not parse date from RINEX file name '
'{}'.format(rinex_fname))
python类strptime()的实例源码
def __init__(self, glo_status_fname=GLO_STATUS_FNAME):
"""
Parse *glo_status_fname* and store GLONASS status information.
"""
super(GLONASS_Status, self).__init__()
if glo_status_fname == GLO_STATUS_FNAME and not os.path.isfile(glo_status_fname):
update_glo_status()
def parse_dt(date, time):
if date == '0000-00-00' and time == '00:00':
return None
else:
return datetime.strptime(date + ' ' + time,
'%Y-%m-%d %H:%M')
with open(glo_status_fname) as fid:
for line in fid:
if line.startswith('#'):
continue
toks = line.split()
launch_dt = parse_dt(toks[0], toks[1])
start_dt = parse_dt(toks[2], toks[3])
end_dt = parse_dt(toks[4], toks[5])
slot, freq, plane, GLONASS, cosmos = map(int, toks[6:])
interval = DateTimeInterval.closed_open(start_dt, end_dt)
info = StatusInfo(launch_dt, slot, freq, plane, GLONASS, cosmos)
self.setdefault(slot, OrderedDict())[interval] = info
def parse(omni_fname,
colspecs=COLSPECS,
names=NAMES,
na_values=NA_VALUES):
"""
Parse the OMNI data record *omni_fname* and return a
:class:`DataFrame`. To parse, use the fixed columns *colspecs*,
the column identifiers *names*, and acceptable NaN column mapping
*na_values*.
"""
df = PD.read_fwf(omni_fname,
colspecs=colspecs,
header=None,
names=names,
na_values=na_values,
parse_dates={'date': [0, 1, 2, 3]},
date_parser=lambda x: datetime.strptime(x, '%Y %j %H %M'))
df.set_index('date', inplace=True)
return df
def toDict(self):
return {'user_id': self.user_id,
'project_id': self.project_id,
'is_admin': self.is_admin,
'read_deleted': self.read_deleted,
'roles': self.roles,
'remote_address': self.remote_address,
'timestamp': datetime.strptime(self.timestamp,
'%Y-%m-%dT%H:%M:%S.%f'),
'request_id': self.request_id,
'auth_token': self.auth_token,
'quota_class': self.quota_class,
'user_name': self.user_name,
'service_catalog': self.service_catalog,
'project_name': self.project_name,
'instance_lock_checked': self.instance_lock_checked,
'tenant': self.tenant,
'user': self.user}
def objectHookHandler(json_dict):
for key, value in json_dict.items():
if isinstance(value, dict):
json_dict[key] = objectHookHandler(value)
else:
try:
json_dict[key] = datetime.strptime(value,
"%Y-%m-%dT%H:%M:%S.%f")
except Exception as ex:
pass
if "synergy_object" in json_dict:
synergy_object = json_dict["synergy_object"]
try:
objClass = import_class(synergy_object["name"])
objInstance = objClass()
return objInstance.deserialize(json_dict)
except SynergyError as ex:
raise ex
else:
return json_dict
def _compute_name(self):
comp_name = '/'
for hc_res_clinical_impression in self:
if hc_res_clinical_impression.subject_type == 'patient':
comp_name = hc_res_clinical_impression.subject_patient_id.name
if hc_res_clinical_impression.subject_patient_id.birth_date:
subject_patient_birth_date = datetime.strftime(datetime.strptime(hc_res_clinical_impression.subject_patient_id.birth_date, DF), "%Y-%m-%d")
comp_name = comp_name + "("+ subject_patient_birth_date + "),"
if hc_res_clinical_impression.subject_type == 'group':
comp_name = hc_res_clinical_impression.subject_group_id.name + ","
if hc_res_clinical_impression.code_id:
comp_name = comp_name + " " + hc_res_clinical_impression.code_id.name + "," or ''
if hc_res_clinical_impression.date:
patient_date = datetime.strftime(datetime.strptime(hc_res_clinical_impression.date, DTF), "%Y-%m-%d")
comp_name = comp_name + " " + patient_date
hc_res_clinical_impression.name = comp_name
def _compute_name(self):
comp_name = '/'
for hc_res_condition in self:
if hc_res_condition.subject_type == 'patient':
comp_name = hc_res_condition.subject_patient_id.name
if hc_res_condition.subject_patient_id.birth_date:
subject_patient_birth_date = datetime.strftime(datetime.strptime(hc_res_condition.subject_patient_id.birth_date, DF), "%Y-%m-%d")
comp_name = comp_name + "("+ subject_patient_birth_date + ")"
if hc_res_condition.subject_type == 'group':
comp_name = hc_res_condition.subject_group_id.name
if hc_res_condition.code_id:
comp_name = comp_name + ", " + hc_res_condition.code_id.name or ''
if hc_res_condition.asserted_date:
patient_asserted_date = datetime.strftime(datetime.strptime(hc_res_condition.asserted_date, DTF), "%Y-%m-%d")
comp_name = comp_name + ", " + patient_asserted_date
hc_res_condition.name = comp_name
def _compute_name(self):
comp_name = '/'
for hc_res_encounter in self:
if hc_res_encounter.subject_type == 'patient':
comp_name = hc_res_encounter.subject_patient_id.name
if hc_res_encounter.subject_patient_id.birth_date:
subject_patient_birth_date = datetime.strftime(datetime.strptime(hc_res_encounter.subject_patient_id.birth_date, DF), "%Y-%m-%d")
comp_name = comp_name + "("+ subject_patient_birth_date + ")"
if hc_res_encounter.subject_type == 'group':
comp_name = hc_res_encounter.subject_group_id.name
# if hc_res_encounter.type_id:
# comp_name = comp_name + ", " + hc_res_encounter.type_id.name or ''
if hc_res_encounter.start_date:
subject_start_date = datetime.strftime(datetime.strptime(hc_res_encounter.start_date, DTF), "%Y-%m-%d")
comp_name = comp_name + ", " + subject_start_date
hc_res_encounter.name = comp_name
def _get_time_obj(time_str):
"""
In some ESM versions the time format is YYYY/MM/DD instead of
DD/MM/YYYY. This detects and normalizes to the latter.
Args:
last_time (str): timestamp in format 'YYYY/MM/DD HH:MM:SS'
or 'DD/MM/YYYY HH:MM:SS'
Returns:
str of timestamp in 'DD/MM/YYYY HH:MM:SS' format
or None if neither format matches
"""
time_format1 = '%m/%d/%Y %H:%M:%S'
time_format2 = '%Y/%m/%d %H:%M:%S'
try:
time_obj = datetime.strptime(time_str, time_format1)
except ValueError:
try:
time_obj = datetime.strptime(time_str, time_format2)
except ValueError:
logging.debug('Invalid time format: {}'.format(time_str))
time_obj = None
return time_obj
def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""
Helper to create a parse action for converting parsed datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt)
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""
Helper to create a parse action for converting parsed datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt)
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
def setUp(self):
self.config_cv = {
'start_date':'2014-01-01',
'end_date':'2014-05-05',
'train_on':{'days':0, 'weeks':5},
'test_on':{'days':0, 'weeks':1},
'fake_freq':'6W'
}
d_labels = {'response' : pd.Series([1.18, 1.28], index=[0,1]),
'Feces_kg_day' : pd.Series([1.18, 1.28], index=[0,1]),
'ToiletID' : pd.Series(['a08D000000PXgspIAD', 'a08D000000PXgspIAD'], index=[0,1]),
'Collection_Date': pd.Series([datetime.strptime('2014-10-16','%Y-%m-%d'), datetime.strptime('2014-10-17','%Y-%m-%d')], index=[0,1])
}
d_feat = {'Total_Waste_kg_day' : pd.Series([7.13, 7.63], index=[0,1]),
'ToiletID' : pd.Series(['a08D000000PXgspIAD', 'a08D000000PXgspIAD'], index=[0,1]),
'Collection_Date': pd.Series([datetime.strptime('2014-10-16','%Y-%m-%d'), datetime.strptime('2014-10-17','%Y-%m-%d')], index=[0,1]),
'Feces_kg_day_lag1' : pd.Series([0, 1.18], index=[0,1]),
'Feces_kg_day_lag2' : pd.Series([0, 0], index=[0,1]),
'Feces_kg_day_lag3' : pd.Series([0, 0], index=[0,1])
}
self.features_big = pd.DataFrame(d_feat)
self.labels_big = pd.DataFrame(d_labels)
def _read_task_metadata(self, task_dir):
"""Read the meta file containing core fields for dstat."""
try:
with open(os.path.join(task_dir, 'meta.yaml'), 'r') as f:
meta = yaml.load('\n'.join(f.readlines()))
# Make sure that create-time string is turned into a datetime
meta['create-time'] = datetime.strptime(meta['create-time'],
'%Y-%m-%d %H:%M:%S.%f')
return meta
except (IOError, OSError):
# lookup_job_tasks may try to read the task metadata as a task is being
# created. In that case, just catch the exception and return None.
return None
def date_prompt(self):
print("")
print("existing hours: ")
for i, entry in enumerate(self.time_log.values()):
weekday = DAY_INDEX[datetime.strptime(str(entry.date), "%Y-%m-%d").weekday()]
if entry.holiday:
print("[{0:2}] {1:3} {2} - {3} hours - {4}".format(i, weekday, entry.date, entry.time, entry.holiday)) # item(ISO date, existing hours)
else:
print("[{0:2}] {1:3} {2} - {3} hours".format(i, weekday, entry.date, entry.time)) # item(ISO date, existing hours)
date_index = input("select date(s): ")
print("")
if date_index.find("-") != -1:
date_range = date_index.split("-")
if len(date_range) != 2:
print("Invalid date selection. Expected int or range (i.e., '1-5').")
return
else:
self.entry_prompt(list(
range(int(date_range[0]), int(date_range[1]) + 1)
))
else:
try:
self.entry_prompt(int(date_index))
except ValueError:
print("Invalid date selection. Expected int or range (i.e., '1-5').")
def get_evaluations(cls, start_date, end_date, dx):
""" Return evaluation info """
Evaluation = Pool().get('gnuhealth.patient.evaluation')
start_date = datetime.strptime(str(start_date), '%Y-%m-%d')
end_date = datetime.strptime(str(end_date), '%Y-%m-%d')
end_date += relativedelta(hours=+23,minutes=+59,seconds=+59)
clause = [
('evaluation_start', '>=', start_date),
('evaluation_start', '<=', end_date),
]
if dx:
clause.append(('diagnosis', '=', dx))
res = Evaluation.search(clause)
return(res)
def count_evaluations(cls, start_date, end_date, dx):
""" count diagnoses by groups """
Evaluation = Pool().get('gnuhealth.patient.evaluation')
start_date = datetime.strptime(str(start_date), '%Y-%m-%d')
end_date = datetime.strptime(str(end_date), '%Y-%m-%d')
end_date += relativedelta(hours=+23,minutes=+59,seconds=+59)
clause = [
('evaluation_start', '>=', start_date),
('evaluation_start', '<=', end_date),
('diagnosis', '=', dx),
]
res = Evaluation.search_count(clause)
return(res)
def deserialize_column(self, column, value):
if value is None:
return None
if isinstance(column.type, sqltypes.DateTime):
return datetime.strptime(value, self.DATETIME_FORMAT)
if isinstance(column.type, sqltypes.Time):
hour, minute, second = value.split(':')
return time(int(hour), int(minute), int(second))
if isinstance(column.type, sqltypes.Integer):
return int(value)
if isinstance(column.type, sqltypes.Float):
return float(value)
return value
def get(self):
cluster = self.get_argument('cluster')
fr = self.get_argument('fr', default='1970-01-01T00:00:00.000000')
to = self.get_argument('to', default='2200-01-01T00:00:00.000000')
# Parse the dates
fr = datetime.strptime(fr, "%Y-%m-%dT%H:%M:%S.%f")
to = datetime.strptime(to, "%Y-%m-%dT%H:%M:%S.%f")
logs = list()
for log_line in DB.session.query(
ClusterLog
).filter(and_(ClusterLog.cluster == cluster,
ClusterLog.when < to,
ClusterLog.when > fr)).all():
logs.append(log_line.to_dict())
self.set_status(200)
self.write(json.dumps(logs).encode('utf-8'))