import pytz import datetime def string_to_datetime( s ): if s is None: return None try: return datetime.datetime.strptime( s, "%Y-%m-%dT%H:%M:%S.%fZ" ).replace( tzinfo = pytc.utc ) except ValueError: return datetime.datetime.strptime( s, "%Y-%m-%dT%H:%M:%SZ" ).replace( tzinfo = pytc.utc ) def datetime_to_string( dt ): if dt is None: return None return dt.astimezone( pytz.utc ).strftime( "%Y-%m-%dT%H:%M:%S.%fZ" )