Ajout de fonctions generalizedTimeFormat <-> datetime

This commit is contained in:
Pierre-Elliott Bécue 2015-02-23 15:13:40 +01:00
parent 8eae322ab1
commit fb542de099

View file

@ -34,6 +34,7 @@ import calendar
import netaddr
import re
import time
import datetime
import smtplib
import sys
import os
@ -49,6 +50,11 @@ from unicodedata import normalize
import subprocess
from netifaces import interfaces, ifaddresses, AF_INET
try:
import pytz
except:
pytz = None
DEVNULL = open(os.devnull, 'w')
def find_rid_plage(rid):
@ -334,3 +340,52 @@ def from_generalized_time_format(gtf):
"""
return time.mktime(time.strptime(gtf.split("-", 1)[0].split("+", 1)[0].split('Z', 1)[0], "%Y%m%d%H%M%S"))
def datetime_from_generalized_time_format(gtf):
"""Returns a datetime from generalized time format
"""
if '-' in gtf or '+' in gtf:
date, tz = gtf[0:14], gtf[14:]
else:
date = gtf.replace("Z", '')
tz = '0000'
tz = tz.replace('+', '')
the_date = datetime.datetime.strptime(date, "%Y%m%d%H%M%S")
if pytz is not None:
tz_dict = build_tz_dict()
the_timezone = tz_dict.get(tz, pytz.utc)
the_date = the_timezone.localize(the_date)
return the_date
def datetime_to_generalized_time_format(datetime_obj):
"""Transforms a datetime to a GTF"""
if datetime_obj.utcoffset() is None:
if pytz is not None:
datetime_obj = pytz.utc.localize(datetime_obj)
to_append = ""
else:
to_append = "Z"
mostly_gtf = datetime.datetime.strftime(datetime_obj, "%Y%m%d%H%M%S%z")
return mostly_gtf.replace('+0000', "Z") + to_append
def build_tz_dict():
"""Crappy way to define a dict containing all timezones that
pytz can handle.
It seems there is no way to get a tz object from the offset
with pytz.
"""
tz_dict = {}
for tz in pytz.common_timezones:
mytz = pytz.timezone(tz)
d = datetime.datetime.now(mytz).utcoffset().total_seconds()
hours = int(d)/3600
minutes = int(float(int(d) % 3600)/60)
fmt = "%s%02d%02d" % (sgn(hours), abs(hours), minutes)
if fmt not in tz_dict:
tz_dict[fmt] = mytz
return tz_dict
sgn = lambda x: '-' if x < 0 else ''