Coverage for /home/martinb/workspace/client-py/fhirclient/models/fhirdate.py : 67%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Facilitate working with dates.
5# 2014, SMART Health IT.
7import sys
8import logging
9import isodate
10import datetime
12logger = logging.getLogger(__name__)
15class FHIRDate(object):
16 """ Facilitate working with dates.
18 - `date`: datetime object representing the receiver's date-time
19 """
21 def __init__(self, jsonval=None):
22 self.date = None
23 if jsonval is not None:
24 isstr = isinstance(jsonval, str)
25 if not isstr and sys.version_info[0] < 3: # Python 2.x has 'str' and 'unicode'
26 isstr = isinstance(jsonval, basestring)
27 if not isstr:
28 raise TypeError("Expecting string when initializing {}, but got {}"
29 .format(type(self), type(jsonval)))
30 try:
31 if 'T' in jsonval:
32 self.date = isodate.parse_datetime(jsonval)
33 else:
34 self.date = isodate.parse_date(jsonval)
35 except Exception as e:
36 logger.warning("Failed to initialize FHIRDate from \"{}\": {}"
37 .format(jsonval, e))
39 self.origval = jsonval
41 def __setattr__(self, prop, value):
42 if 'date' == prop:
43 self.origval = None
44 object.__setattr__(self, prop, value)
46 @property
47 def isostring(self):
48 if self.date is None:
49 return None
50 if isinstance(self.date, datetime.datetime):
51 return isodate.datetime_isoformat(self.date)
52 return isodate.date_isoformat(self.date)
54 @classmethod
55 def with_json(cls, jsonobj):
56 """ Initialize a date from an ISO date string.
57 """
58 isstr = isinstance(jsonobj, str)
59 if not isstr and sys.version_info[0] < 3: # Python 2.x has 'str' and 'unicode'
60 isstr = isinstance(jsonobj, basestring)
61 if isstr:
62 return cls(jsonobj)
64 if isinstance(jsonobj, list):
65 return [cls(jsonval) for jsonval in jsonobj]
67 raise TypeError("`cls.with_json()` only takes string or list of strings, but you provided {}"
68 .format(type(jsonobj)))
70 @classmethod
71 def with_json_and_owner(cls, jsonobj, owner):
72 """ Added for compatibility reasons to FHIRElement; "owner" is
73 discarded.
74 """
75 return cls.with_json(jsonobj)
77 def as_json(self):
78 if self.origval is not None:
79 return self.origval
80 return self.isostring