comparison sat/tools/common/date_utils.py @ 2825:1b6547fb80da

tools(common/date_utils): fixed order on year first + set default date for date_parse
author Goffi <goffi@goffi.org>
date Fri, 01 Mar 2019 15:35:55 +0100
parents 7968c8b7b5e1
children ab2696e34d29
comparison
equal deleted inserted replaced
2824:0ae25883e223 2825:1b6547fb80da
31 import re 31 import re
32 32
33 RELATIVE_RE = re.compile(ur"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *" 33 RELATIVE_RE = re.compile(ur"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
34 ur"(?P<unit>(second|minute|hour|day|week|month|year))s?" 34 ur"(?P<unit>(second|minute|hour|day|week|month|year))s?"
35 ur"(?P<ago> +ago)?", re.I) 35 ur"(?P<ago> +ago)?", re.I)
36 36 YEAR_FIRST_RE = re.compile(ur"\d{4}[^\d]+")
37 TZ_UTC = tz.tzutc() 37 TZ_UTC = tz.tzutc()
38 TZ_LOCAL = tz.gettz() 38 TZ_LOCAL = tz.gettz()
39 # used to replace values when something is missing
40 DEFAULT_DATETIME = datetime.datetime(2000, 01, 01)
39 41
40 42
41 def date_parse(value, default_tz=TZ_UTC): 43 def date_parse(value, default_tz=TZ_UTC):
42 """Parse a date and return corresponding unix timestamp 44 """Parse a date and return corresponding unix timestamp
43 45
44 @param value(unicode): date to parse, in any format supported by parser 46 @param value(unicode): date to parse, in any format supported by parser
45 @param default_tz(datetime.tzinfo): default timezone 47 @param default_tz(datetime.tzinfo): default timezone
46 @return (int): timestamp 48 @return (int): timestamp
47 """ 49 """
48 dt = default_tzinfo(parser.parse(unicode(value), dayfirst=True), default_tz) 50 value = unicode(value).strip()
51 dayfirst = False if YEAR_FIRST_RE.match(value) else True
52
53 dt = default_tzinfo(
54 parser.parse(value, default=DEFAULT_DATETIME, dayfirst=dayfirst),
55 default_tz)
49 return calendar.timegm(dt.utctimetuple()) 56 return calendar.timegm(dt.utctimetuple())
50 57
51 def date_parse_ext(value, default_tz=TZ_UTC): 58 def date_parse_ext(value, default_tz=TZ_UTC):
52 """Extended date parse which accept relative date 59 """Extended date parse which accept relative date
53 60