summaryrefslogtreecommitdiff
path: root/util.py
diff options
context:
space:
mode:
authorAnthon van der Neut <anthon@mnt.org>2021-10-31 21:15:37 +0100
committerAnthon van der Neut <anthon@mnt.org>2021-10-31 21:15:37 +0100
commit930a54b4685b5a259819d1f069c95b3bb674b681 (patch)
tree9665aa00883a4d9dd071bf0c7567c60fa7113400 /util.py
parentbaf8bf17c714aca91083bfdeb734aa5b607d236c (diff)
downloadruamel.yaml-930a54b4685b5a259819d1f069c95b3bb674b681.tar.gz
extract timestamp matching/creation to util.py0.17.17
Diffstat (limited to 'util.py')
-rw-r--r--util.py58
1 files changed, 58 insertions, 0 deletions
diff --git a/util.py b/util.py
index 8c7af47..c2ab46f 100644
--- a/util.py
+++ b/util.py
@@ -4,6 +4,7 @@
some helper functions that might be generally useful
"""
+import datetime
from functools import partial
import re
@@ -48,6 +49,63 @@ class LazyEval:
RegExp = partial(LazyEval, re.compile)
+timestamp_regexp = RegExp(
+ """^(?P<year>[0-9][0-9][0-9][0-9])
+ -(?P<month>[0-9][0-9]?)
+ -(?P<day>[0-9][0-9]?)
+ (?:((?P<t>[Tt])|[ \\t]+) # explictly not retaining extra spaces
+ (?P<hour>[0-9][0-9]?)
+ :(?P<minute>[0-9][0-9])
+ :(?P<second>[0-9][0-9])
+ (?:\\.(?P<fraction>[0-9]*))?
+ (?:[ \\t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
+ (?::(?P<tz_minute>[0-9][0-9]))?))?)?$""",
+ re.X,
+)
+
+
+def create_timestamp(
+ year, month, day, t, hour, minute, second, fraction, tz, tz_sign, tz_hour, tz_minute
+):
+ year = int(year)
+ month = int(month)
+ day = int(day)
+ if not hour:
+ return datetime.date(year, month, day)
+ hour = int(hour)
+ minute = int(minute)
+ second = int(second)
+ if fraction:
+ frac = 0
+ frac_s = fraction[:6]
+ while len(frac_s) < 6:
+ frac_s += '0'
+ frac = int(frac_s)
+ if len(fraction) > 6 and int(fraction[6]) > 4:
+ frac += 1
+ fraction = frac
+ else:
+ fraction = 0
+ delta = None
+ if tz_sign:
+ tz_hour = int(tz_hour)
+ tz_minute = int(tz_minute) if tz_minute else 0
+ delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
+ if tz_sign == '-':
+ delta = -delta
+ # should do something else instead (or hook this up to the preceding if statement
+ # in reverse
+ # if delta is None:
+ # return datetime.datetime(year, month, day, hour, minute, second, fraction)
+ # return datetime.datetime(year, month, day, hour, minute, second, fraction,
+ # datetime.timezone.utc)
+ # the above is not good enough though, should provide tzinfo. In Python3 that is easily
+ # doable drop that kind of support for Python2 as it has not native tzinfo
+ data = datetime.datetime(year, month, day, hour, minute, second, fraction)
+ if delta:
+ data -= delta
+ return data
+
# originally as comment
# https://github.com/pre-commit/pre-commit/pull/211#issuecomment-186466605