Exemplo n.º 1
0
 def testMSTruncated(self):
     # milliseconds are kept but microseconds are lost after rounding.
     self.check(
         datetime(year=2000,
                  month=12,
                  day=25,
                  microsecond=500500,
                  tzinfo=TimeZoneInfo.utc()),
         datetime(year=2000,
                  month=12,
                  day=25,
                  microsecond=500000,
                  tzinfo=TimeZoneInfo.utc()))
Exemplo n.º 2
0
def __force_get_olson_tz_name():
    """
    Retrieve the name of the local timezone in a format
    used by the OLSON timezone database (eg. like "Europe/Moscow").

    >>> tzname = __force_get_olson_tz_name()
    >>> import pytz
    >>> pytz.timezone(tzname) is not None
    True

    @rtype: basestring
    """
    try:
        if sys.platform == 'win32':
            global __win32timezone_to_en

            if __win32timezone_to_en is None:
                __win32timezone_to_en = \
                    dict(TimeZoneInfo._get_indexed_time_zone_keys('Std'))

            # Get timezone name, probably in local language
            win32tz_name = TimeZoneInfo.local().timeZoneName
            # Get the timezone name in English language,
            # like "Russian Standard Time"
            win32timezone_name_en = __win32timezone_to_en.get(win32tz_name,
                                                              win32tz_name)
            olson_tz = __convert_tz_name_win_to_olson(win32timezone_name_en)
            if olson_tz is None:
                raise Exception('Can not retrieve olson tz name')
            else:
                return olson_tz

        elif sys.platform.startswith('linux'):
            with open('/etc/timezone', 'r') as fh:
                return fh.read().strip()

        elif sys.platform == 'darwin':
            return os.readlink('/etc/localtime').strip('/usr/share/zoneinfo/')

        else:
            raise NotImplementedError(sys.platform)

    except NotImplementedError as e:
        raise

    except Exception as e:
        logger.exception('Cannot get the local timezone, using default')
        return ''
Exemplo n.º 3
0
def __force_get_olson_tz_name():
    """
    Retrieve the name of the local timezone in a format
    used by the OLSON timezone database (eg. like "Europe/Moscow").

    >>> tzname = __force_get_olson_tz_name()
    >>> import pytz
    >>> pytz.timezone(tzname) is not None
    True

    @rtype: basestring
    """
    try:
        if sys.platform == 'win32':
            global __win32timezone_to_en

            if __win32timezone_to_en is None:
                __win32timezone_to_en = \
                    dict(TimeZoneInfo._get_indexed_time_zone_keys('Std'))

            # Get timezone name, probably in local language
            win32tz_name = TimeZoneInfo.local().timeZoneName
            # Get the timezone name in English language,
            # like "Russian Standard Time"
            win32timezone_name_en = __win32timezone_to_en.get(
                win32tz_name, win32tz_name)
            olson_tz = __convert_tz_name_win_to_olson(win32timezone_name_en)
            if olson_tz is None:
                raise Exception('Can not retrieve olson tz name')
            else:
                return olson_tz

        elif sys.platform.startswith('linux'):
            with open('/etc/timezone', 'r') as fh:
                return fh.read().strip()

        elif sys.platform == 'darwin':
            return os.readlink('/etc/localtime').strip('/usr/share/zoneinfo/')

        else:
            raise NotImplementedError(sys.platform)

    except NotImplementedError as e:
        raise

    except Exception as e:
        logger.exception('Cannot get the local timezone, using default')
        return ''
Exemplo n.º 4
0
 def testLocal(self):
     self.check(
         datetime(year=2000,
                  month=12,
                  day=25,
                  microsecond=500000,
                  tzinfo=TimeZoneInfo.local()))
Exemplo n.º 5
0
 def testUTC(self):
     self.check(
         datetime(
             year=2000,
             month=12,
             day=25,
             microsecond=500000,
             tzinfo=TimeZoneInfo.utc(),
         )
     )
Exemplo n.º 6
0
    def testFileTimes(self):
        if issubclass(pywintypes.TimeType, datetime.datetime):
            from win32timezone import TimeZoneInfo
            now = datetime.datetime.now(tz=TimeZoneInfo.local())
            nowish = now + datetime.timedelta(seconds=1)
            later = now + datetime.timedelta(seconds=120)
        else:
            rc, tzi = win32api.GetTimeZoneInformation()
            bias = tzi[0]
            if rc == 2:  # daylight-savings is in effect.
                bias += tzi[-1]
            bias *= 60  # minutes to seconds...
            tick = int(time.time())
            now = pywintypes.Time(tick + bias)
            nowish = pywintypes.Time(tick + bias + 1)
            later = pywintypes.Time(tick + bias + 120)

        filename = tempfile.mktemp("-testFileTimes")
        # Windows docs the 'last time' isn't valid until the last write
        # handle is closed - so create the file, then re-open it to check.
        open(filename, "w").close()
        f = win32file.CreateFile(
            filename,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0,
            None,
            win32con.OPEN_EXISTING,
            0,
            None)
        try:
            ct, at, wt = win32file.GetFileTime(f)
            self.assertTrue(
                ct >= now, "File was created in the past - now=%s, created=%s" %
                (now, ct))
            self.assertTrue(now <= ct <= nowish, (now, ct))
            self.assertTrue(
                wt >= now, "File was written-to in the past now=%s, written=%s" %
                (now, wt))
            self.assertTrue(now <= wt <= nowish, (now, wt))

            # Now set the times.
            win32file.SetFileTime(f, later, later, later)
            # Get them back.
            ct, at, wt = win32file.GetFileTime(f)
            # XXX - the builtin PyTime type appears to be out by a dst offset.
            # just ignore that type here...
            if issubclass(pywintypes.TimeType, datetime.datetime):
                self.assertEqual(ct, later)
                self.assertEqual(at, later)
                self.assertEqual(wt, later)

        finally:
            f.Close()
            os.unlink(filename)
Exemplo n.º 7
0
    def testFileTimes(self):
        from win32timezone import TimeZoneInfo

        # now() is always returning a timestamp with microseconds but the
        # file APIs all have zero microseconds, so some comparisons fail.
        now = datetime.datetime.now(tz=TimeZoneInfo.utc()).replace(
            microsecond=0)
        nowish = now + datetime.timedelta(seconds=1)
        later = now + datetime.timedelta(seconds=120)

        filename = tempfile.mktemp("-testFileTimes")
        # Windows docs the 'last time' isn't valid until the last write
        # handle is closed - so create the file, then re-open it to check.
        open(filename, "w").close()
        f = win32file.CreateFile(
            filename,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0,
            None,
            win32con.OPEN_EXISTING,
            0,
            None,
        )
        try:
            ct, at, wt = win32file.GetFileTime(f)
            self.failUnless(
                ct >= now,
                "File was created in the past - now=%s, created=%s" %
                (now, ct),
            )
            self.failUnless(now <= ct <= nowish, (now, ct))
            self.failUnless(
                wt >= now,
                "File was written-to in the past now=%s, written=%s" %
                (now, wt),
            )
            self.failUnless(now <= wt <= nowish, (now, wt))

            # Now set the times.
            win32file.SetFileTime(f, later, later, later, UTCTimes=True)
            # Get them back.
            ct, at, wt = win32file.GetFileTime(f)
            # XXX - the builtin PyTime type appears to be out by a dst offset.
            # just ignore that type here...
            self.failUnlessEqual(ct, later)
            self.failUnlessEqual(at, later)
            self.failUnlessEqual(wt, later)

        finally:
            f.Close()
            os.unlink(filename)
Exemplo n.º 8
0
    def testFileTimes(self):
        if issubclass(pywintypes.TimeType, datetime.datetime):
            from win32timezone import TimeZoneInfo
            now = datetime.datetime.now(tz=TimeZoneInfo.local())
            nowish = now + datetime.timedelta(seconds=1)
            later = now + datetime.timedelta(seconds=120)
        else:
            rc, tzi = win32api.GetTimeZoneInformation()
            bias = tzi[0]
            if rc==2: # daylight-savings is in effect.
                bias += tzi[-1]
            bias *= 60 # minutes to seconds...
            tick = int(time.time())
            now = pywintypes.Time(tick+bias)
            nowish = pywintypes.Time(tick+bias+1)
            later = pywintypes.Time(tick+bias+120)

        filename = tempfile.mktemp("-testFileTimes")
        # Windows docs the 'last time' isn't valid until the last write
        # handle is closed - so create the file, then re-open it to check.
        open(filename,"w").close()
        f = win32file.CreateFile(filename, win32file.GENERIC_READ|win32file.GENERIC_WRITE,
                                 0, None,
                                 win32con.OPEN_EXISTING, 0, None)
        try:
            ct, at, wt = win32file.GetFileTime(f)
            self.failUnless(ct >= now, "File was created in the past - now=%s, created=%s" % (now, ct))
            self.failUnless( now <= ct <= nowish, (now, ct))
            self.failUnless(wt >= now, "File was written-to in the past now=%s, written=%s" % (now,wt))
            self.failUnless( now <= wt <= nowish, (now, wt))

            # Now set the times.
            win32file.SetFileTime(f, later, later, later)
            # Get them back.
            ct, at, wt = win32file.GetFileTime(f)
            # XXX - the builtin PyTime type appears to be out by a dst offset.
            # just ignore that type here...
            if issubclass(pywintypes.TimeType, datetime.datetime):
                self.failUnlessEqual(ct, later)
                self.failUnlessEqual(at, later)
                self.failUnlessEqual(wt, later)

        finally:
            f.Close()
            os.unlink(filename)
Exemplo n.º 9
0
__all__ = ['from_excel', 'to_excel']

import pandas as pd
import numpy as np

from pywintypes import TimeType
from datetime import datetime
from functools import singledispatch
from win32timezone import TimeZoneInfo

winUTC = TimeZoneInfo('GMT Standard Time', True)


# A recursive routine to convert Windows dates to naive
# datetime objects, including those found in tuples
@singledispatch
def cleanin(arg):
    return arg


@cleanin.register(TimeType)
def cleanin_timetype(arg):
    return datetime(*arg.timetuple()[:6])


@cleanin.register(tuple)
def cleanin_tuple(arg):
    return tuple(map(cleanin, arg))


# A routine to quickly prune data that will be truncated by Excel.