Пример #1
0
    def astimezone_and_leap_second(self, tz):
        """Convert to a Python ``datetime`` and leap second in a timezone.

        Convert this time to a Python ``datetime`` and a leap second::

            dt, leap_second = t.astimezone_and_leap_second(tz)

        The argument ``tz`` should be a timezone from the third-party
        ``pytz`` package, which must be installed separately.  The date
        and time returned will be for that time zone.

        The leap second value is provided because a Python ``datetime``
        can only number seconds ``0`` through ``59``, but leap seconds
        have a designation of at least ``60``.  The leap second return
        value will normally be ``0``, but will instead be ``1`` if the
        date and time are a UTC leap second.  Add the leap second value
        to the ``second`` field of the ``datetime`` to learn the real
        name of the second.

        If this time is an array, then an array of ``datetime`` objects
        and an array of leap second integers is returned, instead of a
        single value each.

        """
        dt, leap_second = self.utc_datetime_and_leap_second()
        normalize = getattr(tz, 'normalize', None)
        if self.shape and normalize is not None:
            dt = array([normalize(d.astimezone(tz)) for d in dt])
        elif self.shape:
            dt = array([d.astimezone(tz) for d in dt])
        elif normalize is not None:
            dt = normalize(dt.astimezone(tz))
        else:
            dt = dt.astimezone(tz)
        return dt, leap_second
Пример #2
0
def convert_to_localtime(data):
    if args.localtime:  # convert to localtime
        for row in data:
            datetime = iso8601.parse_date(row['time'])
            localdatetime = datetime.astimezone(tzlocal.get_localzone())
            row['time'] = localdatetime.isoformat()
    return data
Пример #3
0
def _utc_datetime_to_tai(leap_dates, leap_offsets, dt):
    if dt.tzinfo is None:
        raise ValueError(_naive_complaint)
    if dt.tzinfo is not utc:
        dt = dt.astimezone(utc)
    return _utc_to_tai(leap_dates, leap_offsets, dt.year, dt.month, dt.day,
                       dt.hour, dt.minute, dt.second + dt.microsecond * 1e-6)
Пример #4
0
def get_event(day, service):
    # Call the Calendar API
    date = datetime.datetime.combine(day, datetime.datetime.datetime.min.time())
    end_date = datetime.datetime.combine(date, datetime.datetime.datetime.min.time())
    utc = pytz.UTC
    date = datetime.astimezone(utc)
    end_date = end_date.astimezone(utc)
    events_result = service.events().list(calendarId='primary', timeMin=now, timeMax=end_date.isformat(),
                                        singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    else:
        speak("You have {len(events)} events on this day.")

        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'])
            start_time = str(start.split("T"[1]).split("-"[0]))
            if int(start_time.split(":")[0]) < 12:
                start_time = start_time + "am"
            else:
                start_time = str(int(start_time.split(":")[0])-12)
                start_time = start_time + "pm"

            speak(event["summary"] + " at " + start_time)
Пример #5
0
def datetime2utc_time(datetime):
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=timezone('utc'))
    utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)
    utc_timetuple = utc_datetime.timetuple()
    utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6
    return utc_time
Пример #6
0
def add_timezone_to_datetime(datetime, timezone):
    # If there is no tzinfo set, datetime assumes machine localtime.
    # pytz localize fixes this when timezone differs from localtime.
    if datetime.tzinfo is None:
        tz = pytz.timezone(timezone)
        return tz.localize(datetime, is_dst=None)
    else:
        return datetime.astimezone(pytz.timezone(timezone))
Пример #7
0
def datetime_format(
    datetime, dt_format
):  # Uses strftime, but considers timezone (only for datetime objects)
    try:
        dt_format = datetime.astimezone(
            tz=pytz.timezone(settings.TIME_ZONE)).strftime(dt_format)
    except Exception:
        dt_format = datetime.strftime(dt_format)
    return dt_format
Пример #8
0
def convert_utcdate_to_datestring(utc_date):
    """This function take a pytz utc date like:
    '2000-03-02 23:00:00+00:00' and converts it to a '03/03/2000'
    formated string. This is returned."""
    # Parse string to datetime
    datetime = dateutil.parser.parse(utc_date)
    # Convert date from UTC to local
    astimezone_date = datetime.astimezone(pytz.timezone('Europe/Paris'))
    # Convert datetime to a date string
    return astimezone_date.strftime("%m/%d/%Y")
Пример #9
0
    def to_utc(self, datetime):
        """Returns a datetime object converted to UTC and without tzinfo.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A naive ``datetime`` object (no timezone), converted to UTC.
        """
        if datetime.tzinfo is None:
            datetime = self.tzinfo.localize(datetime)

        return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
Пример #10
0
    def to_local_timezone(self, datetime):
        """Returns a datetime object converted to the local timezone.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A ``datetime`` object normalized to a timezone.
        """
        if datetime.tzinfo is None:
            datetime = datetime.replace(tzinfo=pytz.UTC)

        return self.tzinfo.normalize(datetime.astimezone(self.tzinfo))
Пример #11
0
    def to_utc(self, datetime):
        """Returns a datetime object converted to UTC and without tzinfo.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A naive ``datetime`` object (no timezone), converted to UTC.
        """
        if datetime.tzinfo is None:
            datetime = self.tzinfo.localize(datetime)

        return datetime.astimezone(pytz.UTC).replace(tzinfo=None)
Пример #12
0
    def to_local_timezone(self, datetime):
        """Returns a datetime object converted to the local timezone.

        :param datetime:
            A ``datetime`` object.
        :returns:
            A ``datetime`` object normalized to a timezone.
        """
        if datetime.tzinfo is None:
            datetime = datetime.replace(tzinfo=pytz.UTC)

        return self.tzinfo.normalize(datetime.astimezone(self.tzinfo))
Пример #13
0
def datetime2utc_time(datetime):
    # add utc time zone if no time zone is set
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=timezone('utc'))

    # convert to utc time zone from whatever time zone the datetime is set to
    utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)

    # create a time tuple from datetime
    utc_timetuple = utc_datetime.timetuple()

    # create a time element from the tuple an add microseconds
    utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6

    return utc_time
Пример #14
0
    def _normalize_date(self, datetime):
        """Normalizes datetime for SolarEdge API call.

        Normalizes `datetime` to be used in solaredge API, i.e.,
        - timezone is converted to time zone of system location
        - time zone info and microseconds are removed (API fails otherwise)

        Args:
            datetime (datetime.datetime): localized datetime to be normalized

        Raises:
            AssertionError: if datime misses tzinfo

        Returns:
            datetime.datetime: datetime normalized for solaredge API call
        """
        assert datetime.tzinfo is not None, "dates are expected to be localized"
        return datetime.astimezone(self.get_tz()).replace(microsecond=0).replace(tzinfo=None)
Пример #15
0
def datetime_to_str(dt: DateTimeType, in_local_tz=False) -> str:
    """Convert a date time into a string.
    Args:
       dt: the datetime instance to convert.
       in_local_tz: if True, the string returned will represent the \
         time (dt) in the local timezone (previously set by :meth:`set_local_timezone`)\
         Otherwise, dt is converted as is (i.e. in the timezone provided)
    Returns:
       the datetime information in ISO format.
    Raises:
       RuntimeError: if in_local_tz is True and the local time zone has not been set.
    """
    my_time = dt
    if in_local_tz:
        if _tzinfo is None:
            raise RuntimeError("Must set the local time zone first")
        my_time = dt.astimezone(_tzinfo)
    return my_time.isoformat(sep=' ', timespec='seconds')
Пример #16
0
def convert_extracted_time(datetime):
    """
    NearBeach stores its time in UTC. This function is designed to get the UTC time and convert it into
    the correct timezone, and from there it then converts the time into a dictionary model (hour, minutes, AM/PM)
    and returns that.
    :param datetime: this will be the datetime extract from the model
    :return: { 'hour': hour, 'minute': minute, 'meridiem': meridiem }
    """
    datetime = datetime.replace(tzinfo=pytz.utc) #Make sure Django knows its in UTC time
    datetime_converted = datetime.astimezone(pytz.timezone(settings.TIME_ZONE))

    #Extract into variables to manipulate into NearBeach format
    year = datetime_converted.year
    month = datetime_converted.month
    day =datetime_converted.day
    hour = datetime_converted.hour
    minute = datetime_converted.minute

    """
    The 24 hours to 12 hours formula.
    00:00 means that it is 12:00 AM - change required for hour
    01:00 means that it is 01:00 AM - no change required
    12:00 means that it is 12:00 PM - change required for meridiem
    13:00 means that it is 01:00 PM - change required for hour and meridiem
    """
    meridiem = u'AM'
    if hour == 0:
        hour = 12
    elif hour == 12:
        meridiem = u'PM'
    elif hour > 12:
        hour = hour - 12
        meridiem = u'PM'

    #Time to return the dictionary
    return {
        'year': year,
        'month': month,
        'day': day,
        'hour': hour,
        'minute': minute,
        'meridiem': meridiem,
    }
Пример #17
0
 def _localize_utc_time(self, datetime):
     return datetime.astimezone(self.local_tz)
Пример #18
0
 def jetlagConvert(self, date, code):
     #TODO: ask for country code and convert to tz ?
     dt = self.tz.localize(date)
     tz = pytz.timezone(pytz.country_timezones[code][0])
     return dt.astimezone(tz).strftime(self.datetime_fmt)
Пример #19
0
def localtime(datetime):
    return datetime.astimezone()
Пример #20
0
 def _utcAndStripTZ(dt):
     return dt.astimezone(eventcalendar.UTC).replace(tzinfo=None)
Пример #21
0
def datetime_convert_timezone(datetime, from_zone, to_zone):
    datetime = datetime.replace(tzinfo=from_zone)
    converted_datetime = datetime.astimezone(to_zone)
    converted_datetime = converted_datetime.replace(tzinfo=None)
    return converted_datetime
Пример #22
0
def set_time_zone(datetime):
    return datetime.astimezone(tz=None)
Пример #23
0
 def _localtime(self, datetime):
     if self.timezone is not None:
         return datetime.astimezone(self.timezone)
     else:
         # Currently assume UTC.
         return datetime
Пример #24
0
def datetime_convert_timezone(datetime, from_zone, to_zone):
    datetime = datetime.replace(tzinfo=from_zone)
    converted_datetime = datetime.astimezone(to_zone)
    converted_datetime = converted_datetime.replace(tzinfo=None)
    return converted_datetime
Пример #25
0
def parse_sunrise_sunset_hour_minute(datetime: Datetime) -> tuple[str, str]:
    return (datetime.astimezone(tz=None).strftime('%-H'),
            datetime.astimezone(tz=None).strftime('%M'))
Пример #26
0
def parse_sunrise_sunset_time(datetime: Datetime) -> str:
    if (datetime == None):
        return 'N/A'
    return datetime.astimezone(tz=None).strftime('%-H:%M')
Пример #27
0
def toUSTZ(datetime):
    datetime = pytz.utc.localize(datetime)
    return datetime.astimezone(user_tz)
Пример #28
0
 def _localtime(self, datetime):
     if self.timezone is not None:
         return datetime.astimezone(self.timezone)
     else:
         # Currently assume UTC.
         return datetime
Пример #29
0
def date_only_tzlocal(datetime: datetime.datetime):
    return datetime.astimezone(dateutil.tz.tzlocal()).date()  # type: ignore
Пример #30
0
def cst(datetime, format='%Y-%m-%d %H:%M'):
    return datetime.astimezone(_tzinfo).strftime(format)
Пример #31
0
def process_sessions():
    settings = get_settings("Copy videos from a Granicus S3 export to YouTube")
    migration = YTMigration()
    client_data = migration.clientGet(settings["email"])

    s3 = S3Utils(client_data["s3_access_key"], client_data["s3_secret_key"],
                 client_data["s3_bucket"])

    migration_info = {
        'summary': {
            'attempted': 0,
            'uploaded': 0,
            'skipped': 0,
            'failed': 0
        },
        'sessions': {
            'attempted': [],
            'uploaded': [],
            'skipped': [],
            'failed': []
        }
    }

    if not client_data:
        pprint(
            "There are no client credentials in the system for the email address provided"
        )
        return

    if 'token' not in client_data or not client_data["token"]:
        pprint(
            "Please authenticate this client first at https://s3-youtube.open.media"
        )
        return

    youtube_client = yt_api_utils.youtube_client_get(client_data)

    sessions = migration.sessionsGet(client_data["id"], 'harvested')
    inclusions = granicus_manual_csv(client_data, "include")
    print("Using manual inclusions file, " + str(len(inclusions)) +
          " sessions")
    exclusions = granicus_manual_csv(client_data, "exclude")

    if sessions:
        counter = 0
        limit = settings["limit"]
        for session in sessions:
            if counter >= limit:
                break

            manual_inclusion = False

            #if there are manual inclusions we only do those
            if inclusions and session["session_id"] and int(
                    session["session_id"]) in inclusions:
                manual_inclusion = True
            elif inclusions:
                migration_info["sessions"]["skipped"].append(sessions)
                continue

            if exclusions and session["session_id"] in exclusions:
                migration_info["sessions"]["skipped"].append(sessions)
                continue

            if not manual_inclusion and settings["start_timestamp"]:
                if not session["session_timestamp"] or session[
                        "session_timestamp"] < settings["start_timestamp"]:
                    migration_info["sessions"]["skipped"].append(session)
                    continue

            if not manual_inclusion and settings["end_timestamp"]:
                if not session["session_timestamp"] or session[
                        "session_timestamp"] > settings["end_timestamp"]:
                    migration_info["sessions"]["skipped"].append(session)
                    continue

            if not manual_inclusion and settings["folder_ids"]:
                if not session["session_folder"] or session[
                        "session_folder"] not in settings["folder_ids"]:
                    migration_info["sessions"]["skipped"].append(session)
                    continue

            if settings["commit"]:
                print("Downloading " + session["title"])
                session = s3_download_file(client_data, s3, session)
                response = yt_api_utils.youtube_upload_session(
                    youtube_client, session)

                if response["id"]:
                    session["youtube_id"] = response["id"]
                    session["status"] = 'uploaded'
                    os.remove(session["local_path"])
                    migration.sessionUpdate(session)
                    migration_info["sessions"]["uploaded"].append(session)
                    pprint("Session uploaded: " + session["title"])
                    if "youtube_playlist" in session:
                        yt_api_utils.youtube_add_session_to_playlist(
                            youtube_client, session)
                else:
                    session["status"] = 'upload failed'
                    migration.sessionUpdate(session)
                    pprint("Session upload failed: " + session["title"])
                    migration_info["sessions"]["failed"].append(session)
            else:
                migration_info["sessions"]["attempted"].append(session)

            counter += 1

    migration_info["summary"]["attempted"] = len(
        migration_info["sessions"]["attempted"])
    migration_info["summary"]["skipped"] = len(
        migration_info["sessions"]["skipped"])
    migration_info["summary"]["uploaded"] = len(
        migration_info["sessions"]["uploaded"])
    migration_info["summary"]["failed"] = len(
        migration_info["sessions"]["failed"])

    if settings["verbose"]:
        print("Sessions:")
        for session in migration_info["sessions"]["attempted"]:
            if session["session_date"]:
                datetime = parser.parse(session["session_date"])
                utcDate = datetime.astimezone(timezone('UTC'))
                title_date = utcDate.strftime("%m/%d/%Y")
            else:
                title_date = "NO DATE"
            print(
                str(session["session_folder"]) + ": " + session["title"] +
                " - " + title_date)

    print("Summary:")
    pprint(migration_info["summary"])
Пример #32
0
 def jetlagConvert(self, date, code):
     #TODO: ask for country code and convert to tz ?
     dt = self.tz.localize(date)
     tz = pytz.timezone(pytz.country_timezones[code][0])
     return dt.astimezone(tz).strftime(self.datetime_fmt)
Пример #33
0
 def lt(datetime):
   #return pytz.timezone('America/Los_Angeles').localize(datetime)
   return datetime.astimezone(pytz.timezone('America/Los_Angeles') )
Пример #34
0
def _to_utc_timestamp(dt):
    if dt.tzinfo is not None:
        dt = dt.astimezone(pytz.UTC)
    return calendar.timegm(dt.timetuple())
Пример #35
0
def set_time_zone(datetime):		
	return datetime.astimezone(tz=None)
Пример #36
0
 def _utcAndStripTZ(dt):
     return dt.astimezone(eventcalendar.UTC).replace(tzinfo=None)
def to_kst(datetime: datetime.datetime):
    return datetime.astimezone(kst).strftime('%Y-%m-%d %H:%M')
Пример #38
0
def datetime_to_timestamp(datetime):
    time_str = str(datetime.astimezone(pytz.timezone(get_dataapi_tz())))[:19]
    # time_str = datetime.strftime("%Y-%m-%d %H:%M:%S")
    return timeformat_to_timestamp(time_str)
Пример #39
0
def utc(datetime, format='%Y-%m-%d %H:%M:%S%z'):
    return datetime.astimezone(tz.gettz('UTC')).strftime(format)