date_utils.py
56 lines
| 1.9 KiB
| text/x-python
|
PythonLexer
r2 | # -*- coding: utf-8 -*- | |||
r112 | # Copyright 2010 - 2017 RhodeCode GmbH and the AppEnlight project authors | |||
r2 | # | |||
r112 | # Licensed under the Apache License, Version 2.0 (the "License"); | |||
# you may not use this file except in compliance with the License. | ||||
# You may obtain a copy of the License at | ||||
r2 | # | |||
r112 | # http://www.apache.org/licenses/LICENSE-2.0 | |||
r2 | # | |||
r112 | # Unless required by applicable law or agreed to in writing, software | |||
# distributed under the License is distributed on an "AS IS" BASIS, | ||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||
# See the License for the specific language governing permissions and | ||||
# limitations under the License. | ||||
r2 | ||||
from datetime import tzinfo, timedelta, datetime | ||||
from dateutil.relativedelta import relativedelta | ||||
import logging | ||||
log = logging.getLogger(__name__) | ||||
def to_relativedelta(time_delta): | ||||
r153 | return relativedelta( | |||
seconds=int(time_delta.total_seconds()), microseconds=time_delta.microseconds | ||||
) | ||||
r2 | ||||
r153 | def convert_date(date_str, return_utcnow_if_wrong=True, normalize_future=False): | |||
r2 | utcnow = datetime.utcnow() | |||
if isinstance(date_str, datetime): | ||||
# get rid of tzinfo | ||||
return date_str.replace(tzinfo=None) | ||||
if not date_str and return_utcnow_if_wrong: | ||||
return utcnow | ||||
try: | ||||
try: | ||||
r153 | if "Z" in date_str: | |||
date_str = date_str[: date_str.index("Z")] | ||||
if "." in date_str: | ||||
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%f") | ||||
r2 | else: | |||
r153 | date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S") | |||
r2 | except Exception: | |||
# bw compat with old client | ||||
r153 | date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S,%f") | |||
r2 | except Exception: | |||
if return_utcnow_if_wrong: | ||||
date = utcnow | ||||
else: | ||||
date = None | ||||
if normalize_future and date and date > (utcnow + timedelta(minutes=3)): | ||||
r153 | log.warning("time %s in future + 3 min, normalizing" % date) | |||
r2 | return utcnow | |||
return date | ||||