Exemple #1
0
 def __init__(self, restrict: bool = True):
     now = _CALI_TZ.localize(dt_datetime.now())
     if restrict and now.hour >= 19:
         raise RuntimeError("Can't run this job after 7 PM (Pacific)!!")
     self._day_0 = now.date()
     self._day_1 = self._day_0 + dt_timedelta(days=1)
     self._timelock = dt_datetime.combine(self._day_0, dt_time.min)
def get_timedelta_in_s(from_value):
    """
    :param from_value: a string representing time in H:M:S
    :return: the value as a timedelta, in seconds
    """
    temp = dt_strptime(from_value, '%H:%M:%S')
    td = dt_timedelta(
        hours=temp.tm_hour, minutes=temp.tm_min, seconds=temp.tm_sec)
    return td.seconds
def get_timedelta_in_s(from_value):
    """
    :param from_value: a string representing time in H:M:S
    :return: the value as a timedelta, in seconds
    """
    temp = dt_strptime(from_value, '%H:%M:%S')
    td = dt_timedelta(hours=temp.tm_hour,
                      minutes=temp.tm_min,
                      seconds=temp.tm_sec)
    return td.seconds
def timedelta(when):
    # FIXME: make DST aware
    whentd = dict()
    for x in ('seconds', 'minutes', 'hours', 'days', 'months', 'years'):
        if x in when and when[x] != None: whentd[x] = when[x]
    if any(whentd):
        logger.debug('WHENTD: {}'.format(whentd))
        return dt_timedelta(**whentd).total_seconds()

    return None
def parse_timestamp(raw_timestamp, use_utc, hints):
    """
    Facebook is highly inconsistent with their timezone formatting.
    Sometimes it's in UTC+/-HH:MM form, and other times its in the
    ambiguous PST, PDT. etc format.

    We have to handle the ambiguity by asking for cues from the user.

    raw_timestamp -- The timestamp string to parse and convert to UTC.
    """
    global FACEBOOK_TIMESTAMP_FORMATS
    timestamp_string, offset = raw_timestamp.rsplit(" ", 1)
    if "UTC+" in offset or "UTC-" in offset:
        if offset[3] == '-':
            offset = [-1 * int(x) for x in offset[4:].split(':')]
        else:
            offset = [int(x) for x in offset[4:].split(':')]
    else:
        offset_hint = hints.get(offset, None)
        if not offset_hint:
            if offset not in TIMEZONE_MAP:
                raise UnexpectedTimeFormatError(raw_timestamp)
            elif len(TIMEZONE_MAP[offset]) > 1:
                raise AmbiguousTimeZoneError(offset, TIMEZONE_MAP[offset])
            offset = list(TIMEZONE_MAP[offset].keys())[0][:2]
        else:
            offset = offset_hint

    if len(offset) == 1:
        # Timezones without minute offset may be formatted
        # as UTC+X (e.g UTC+8)
        offset += [0]

    delta = dt_timedelta(hours=offset[0], minutes=offset[1])

    # Facebook changes the format depending on whether the user is using
    # 12-hour or 24-hour clock settings.
    for number, date_parser in enumerate(_LOCALIZED_DATE_PARSERS):
        timestamp = date_parser.parse(timestamp_string)
        if timestamp is None:
            continue
        # Re-orient the list to ensure that the one that worked is tried first next time.
        if number > 0:
            del FACEBOOK_TIMESTAMP_FORMATS[number]
            FACEBOOK_TIMESTAMP_FORMATS = [date_parser
                                          ] + FACEBOOK_TIMESTAMP_FORMATS
        break
    else:
        raise UnexpectedTimeFormatError(raw_timestamp)
    if use_utc:
        timestamp -= delta
        return timestamp.replace(tzinfo=pytz.utc)
    else:
        return timestamp.replace(tzinfo=TzInfoByOffset(delta))
Exemple #6
0
def getFuzzyDay(t):
	d = localtime(t)
	nt = time()
	n = localtime()
	
	if d[:3] == n[:3]:
		# same day
		date = _("Today")
	elif dt_date.fromtimestamp(t) == dt_date.today() + dt_timedelta(days = 1):
		# next day
		date = _("Tomorrow")
	elif nt < t and (t - nt) < WEEKSECONDS:
		# same week
		date = WEEKDAYS[d.tm_wday]
	else:
		date = "%d.%d.%d" % (d.tm_mday, d.tm_mon, d.tm_year)
		
	return date
def getFuzzyDay(t):
    d = localtime(t)
    nt = time()
    n = localtime()

    if d[:3] == n[:3]:
        # same day
        date = _("Today")
    elif dt_date.fromtimestamp(t) == dt_date.today() + dt_timedelta(days=1):
        # next day
        date = _("Tomorrow")
    elif ((t - nt) < 7 * 86400) and (nt < t):
        # same week
        date = (_("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday"), _("Friday"), _("Saturday"), _("Sunday"))[d[6]]
    elif d[0] == n[0]:
        # same year
        date = "%d.%d.%d" % (d[2], d[1], d[0])
    else:
        date = _("Unknown date")

    return date
def getFuzzyDay(t):
	d = localtime(t)
	nt = time()
	n = localtime()

	if d[:3] == n[:3]:
		# same day
		date = _("Today")
	elif dt_date.fromtimestamp(t) == dt_date.today() + dt_timedelta(days=1):
		# next day
		date = _("Tomorrow")
	elif ((t - nt) < 7 * 86400) and (nt < t):
		# same week
		date = (_("Monday"), _("Tuesday"), _("Wednesday"), _("Thursday"), _("Friday"), _("Saturday"), _("Sunday"))[d[6]]
	elif d[0] == n[0]:
		# same year
		date = "%d.%d.%d" % (d[2], d[1], d[0])
	else:
		date = _("Unknown date")

	return date
 def dst(self, dt):
     return dt_timedelta(seconds=0)
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from collections import defaultdict
from datetime import datetime, tzinfo, time, timedelta as dt_timedelta
import re

import pytz
from pytz.exceptions import NonExistentTimeError, AmbiguousTimeError
from pytz import timezone as pytz_timezone

import arrow
from babel import Locale

_MIN_VALID_TIMEZONE_OFFSET = dt_timedelta(hours=-12)
_MAX_VALID_TIMEZONE_OFFSET = dt_timedelta(hours=14)

# Timestamp formats (language_code, format string, [hints])
#
# "hints" is a dictionary of word -> int translations. Strongly inflected languages,
# such as the Slavic languages, tend to change the endings of day and month names to
# reflect grammatical cases.
#
# The supporting multi-lingual date libraries tend to screw this up a lot of the time,
# so you can add support for missing months. Facebook seems to mess it up on less popular
# languages too...
#
# Days of the week are 1 -> 7 (e.g. Monday -> 1) and months are 1 -> 12 (e.g. January -> 1)
#
# e.g. {'poniedziałek': 1}
Exemple #11
0
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import arrow
from collections import defaultdict
from datetime import datetime, tzinfo, timedelta as dt_timedelta
import pytz
from pytz import timezone as pytz_timezone

_MIN_VALID_TIMEZONE_OFFSET = dt_timedelta(hours=-12)
_MAX_VALID_TIMEZONE_OFFSET = dt_timedelta(hours=14)

# Timestamp formats (language_code, format string)
FACEBOOK_TIMESTAMP_FORMATS = [
    ("en_us", "dddd, MMMM D, YYYY [at] h:mmA"),  # English US (12-hour)
    ("en_us", "dddd, MMMM D, YYYY [at] HH:mm"),  # English US (24-hour)
    ("en_us", "dddd, D MMMM YYYY [at] HH:mm"),  # English UK (24-hour)
    ("nb_no", "D. MMMM YYYY kl. HH:mm"),  # Norwegian (Bokmål)
    ("de_de", "dddd, D. MMMM YYYY [um] HH:mm"),  # German (Germany)
]

# Generate a mapping of all timezones to their offsets.
#
#  e.g. {
#          'PST': {
#              (-7, 0): ['Pacific/US', ...]
#           }
#       }
TIMEZONE_MAP = defaultdict(lambda: defaultdict(set))
for tz_name in pytz.all_timezones: