How to use the datetime.timezone function in DateTime

To help you get started, we’ve selected a few DateTime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aiven / pghoard / test / test_pghoard.py View on Github external
def write_backup_and_wal_files(what):
            for bb, wals in what.items():
                if bb:
                    bb_path = os.path.join(basebackup_storage_path, bb)
                    date_parts = [int(part) for part in bb.replace("_", "-").split("-")]
                    start_time = datetime.datetime(*date_parts, tzinfo=datetime.timezone.utc)
                    with open(bb_path, "wb") as fp:
                        fp.write(b"something")
                    with open(bb_path + ".metadata", "w") as fp:
                        json.dump({
                            "start-wal-segment": wals[0],
                            "start-time": start_time.isoformat(),
                        }, fp)
                for wal in wals:
                    with open(os.path.join(wal_storage_path, wal), "wb") as fp:
                        fp.write(b"something")
github ramonhagenaars / jsons / tests / test_datetime.py View on Github external
def test_load_datetime_with_tz(self):
        tzinfo = datetime.timezone(datetime.timedelta(hours=-2))
        dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34,
                                tzinfo=tzinfo)
        loaded = jsons.load('2018-07-08T21:34:00-02:00')
        self.assertEqual(loaded, dat)
github EJEP / datapoint-python / tests / unit / test_forecast.py View on Github external
test_timestep_0.date = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=2)

        test_timestep_1 = datapoint.Timestep.Timestep()
        test_timestep_1.name = 1
        test_timestep_1.date = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=4)

        test_day_0.timesteps.append(test_timestep_0)
        test_day_0.timesteps.append(test_timestep_1)

        self.forecast.days.append(test_day_0)

        test_day_1 = datapoint.Day.Day()
        for i in range(8):
            ts = datapoint.Timestep.Timestep()
            ts.name = i * 180
            ts.date = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1, hours=i*3)

            test_day_1.timesteps.append(ts)
        self.forecast.days.append(test_day_1)

        # What is being asserted here?
        assert self.forecast.now()
github fact-project / pyfact / tests / test_time.py View on Github external
def test_fjd_to_datetime():
    from fact.time import fjd_to_datetime

    assert fjd_to_datetime(16000.0) == datetime(2013, 10, 22, 0, 0, tzinfo=timezone.utc)
    fjds = pd.Series([0, 365, 18000.5])
    dates = pd.to_datetime(['1970-01-01T00:00Z', '1971-01-01T00:00Z', '2019-04-14T12:00Z'])
    df = pd.DataFrame({'fjds': fjds})
    assert (fjd_to_datetime(fjds) == dates).all()
    assert (fjd_to_datetime(df['fjds']) == pd.Series(dates)).all()
github TheKingOfDuck / logonTracer / logontracer.py View on Github external
addgroups = {}
    removegroups = {}
    sids = {}
    hosts = {}
    dcsync_count = {}
    dcsync = {}
    dcshadow_check = []
    dcshadow = {}
    count = 0
    record_sum = 0
    starttime = None
    endtime = None

    if args.timezone:
        try:
            datetime.timezone(datetime.timedelta(hours=args.timezone))
            tzone = args.timezone
            print("[*] Time zone is %s." % args.timezone)
        except:
            sys.exit("[!] Can't load time zone '%s'." % args.timezone)
    else:
        tzone = 0

    if args.fromdate:
        try:
            fdatetime = datetime.datetime.strptime(args.fromdate, "%Y%m%d%H%M%S")
            print("[*] Parse the EVTX from %s." % fdatetime.strftime("%Y-%m-%d %H:%M:%S"))
        except:
            sys.exit("[!] From date does not match format '%Y%m%d%H%M%S'.")

    if args.todate:
        try:
github den4uk / andriller / andriller / config.py View on Github external
def setup_tz(self):
        tzo = TIME_ZONES.get(self('time_zone'), 0)
        self.tzone = datetime.timezone(datetime.timedelta(hours=tzo))
        self.date_format = ''.join(map(lambda x: f'%{x}' if x.isalpha() else x, self('date_format')))
github digiapulssi / zabbix-monitoring-scripts / etc / zabbix / scripts / kubernetes_monitoring.py View on Github external
python kubernetes_monitoring.py services
"""

# Python imports
from argparse import ArgumentParser
import datetime
import json
import os
import sys

# Retrieve timezone aware system time
if sys.version_info[0] < 3:
    import pytz
    system_time = datetime.datetime.now(pytz.utc)
else:
    system_time = datetime.datetime.now(datetime.timezone.utc)

# 3rd party imports
from kubernetes import client, config

# Loop pods and create discovery
def pods(args, v1):

    pods = v1.list_pod_for_all_namespaces(
        watch=False,
        field_selector=args.field_selector
    )

    # Check pods before listing
    if pods:
        for pod in pods.items:
github chryswoods / acquire / Acquire / ObjectStore / _oci_objstore.py View on Github external
if response.status != 200:
            from Acquire.ObjectStore import ObjectStoreError
            raise ObjectStoreError(
                "Unable to create the PAR '%s': Status %s, Error %s" %
                (str(request), response.status, str(response.data)))

        oci_par = response.data

        if oci_par is None:
            from Acquire.ObjectStore import ObjectStoreError
            raise ObjectStoreError(
                "Unable to create the preauthenticated request!")

        created_datetime = oci_par.time_created.replace(
                                tzinfo=_datetime.timezone.utc)

        expires_datetime = oci_par.time_expires.replace(
                                tzinfo=_datetime.timezone.utc)

        # the URI returned by OCI does not include the server. We need
        # to get the server based on the region of this bucket
        url = _get_object_url_for_region(bucket["region"],
                                         oci_par.access_uri)

        # get the checksum for this URL - used to validate the close
        # request
        from Acquire.Client import PAR as _PAR
        from Acquire.ObjectStore import PARRegistry as _PARRegistry
        url_checksum = _PAR.checksum(url)

        driver_details = {"driver": "oci",
github allegroai / trains / trains / backend_interface / util.py View on Github external
import getpass
import re
from _socket import gethostname
from datetime import datetime
try:
    from datetime import timezone
    utc_timezone = timezone.utc
except ImportError:
    from datetime import tzinfo, timedelta

    class UTC(tzinfo):
        def utcoffset(self, dt):
            return timedelta(0)

        def tzname(self, dt):
            return "UTC"

        def dst(self, dt):
            return timedelta(0)
    utc_timezone = UTC()

from ..backend_api.services import projects
from ..debugging.log import get_logger