78 lines
2.8 KiB
Python
78 lines
2.8 KiB
Python
# combo - content management system
|
|
# Copyright (C) 2015-2018 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
#
|
|
# Code is borrowed from w.c.s. https://dev.entrouvert.org/projects/wcs
|
|
|
|
import datetime
|
|
import time
|
|
|
|
DATE_FORMATS = {
|
|
'C': ['%Y-%m-%d', '%y-%m-%d'],
|
|
'fr': ['%d/%m/%Y', '%d/%m/%y'],
|
|
}
|
|
|
|
DATETIME_FORMATS = {
|
|
'C': ['%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%SZ',
|
|
'%y-%m-%d %H:%M', '%y-%m-%d %H:%M:%S'],
|
|
'fr': ['%d/%m/%Y %H:%M', '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %Hh%M',
|
|
'%d/%m/%y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %Hh%M'],
|
|
}
|
|
|
|
|
|
def get_as_datetime(s):
|
|
formats = []
|
|
for value in DATETIME_FORMATS.values():
|
|
formats.extend(value)
|
|
for value in DATE_FORMATS.values():
|
|
formats.extend(value)
|
|
for format_string in formats:
|
|
try:
|
|
return datetime.datetime.strptime(s, format_string)
|
|
except ValueError:
|
|
pass
|
|
raise ValueError()
|
|
|
|
|
|
def make_date(date_var):
|
|
'''Extract a date from a datetime, a date, a struct_time or a string'''
|
|
if isinstance(date_var, datetime.datetime):
|
|
return date_var.date()
|
|
if isinstance(date_var, datetime.date):
|
|
return date_var
|
|
if isinstance(date_var, time.struct_time) or (
|
|
isinstance(date_var, tuple) and len(date_var) == 9):
|
|
return datetime.date(*date_var[:3])
|
|
try:
|
|
return get_as_datetime(str(date_var)).date()
|
|
except ValueError:
|
|
raise ValueError('invalid date value: %s' % date_var)
|
|
|
|
|
|
def make_datetime(datetime_var):
|
|
'''Extract a date from a datetime, a date, a struct_time or a string'''
|
|
if isinstance(datetime_var, datetime.datetime):
|
|
return datetime_var
|
|
if isinstance(datetime_var, datetime.date):
|
|
return datetime.datetime(year=datetime_var.year, month=datetime_var.month,
|
|
day=datetime_var.day)
|
|
if isinstance(datetime_var, time.struct_time) or (
|
|
isinstance(datetime_var, tuple) and len(datetime_var) == 9):
|
|
return datetime.datetime(*datetime_var[:6])
|
|
try:
|
|
return get_as_datetime(str(datetime_var))
|
|
except ValueError:
|
|
raise ValueError('invalid datetime value: %s' % datetime_var)
|