Python get local time

19 Python code examples are found related to " get local time". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: kernel64.py    From msl-loadlib with MIT License 6 votes vote down vote up
def get_local_time(self):
        """
        Sends a request to the 32-bit server, :class:`~.kernel32.Kernel32`, to
        execute the `kernel32.GetLocalTime <time_>`_ function to get the
        current date and time.

        See the corresponding 32-bit :meth:`~.kernel32.Kernel32.get_time` method.

        .. _time: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724338(v=vs.85).aspx

        Returns
        -------
        :class:`~datetime.datetime` 
            The current date and time.
        """
        return self.request32('get_time') 
Example 2
Source File: Func_lib.py    From Malicious_Domain_Whois with GNU General Public License v3.0 6 votes vote down vote up
def getLocalTime(Timeformat=None, returnType='str'):
    """
    获取本地时间
    :param Timeformat: 需要传入一个时间格式 [默认使用ISO标准]
    :param returnType: 返回数据的类型      [默认为str] 支持datetime/...
    :return: 当前时间(字符串格式)
    """
    __ISOTIMEFORMAT = '%Y-%m-%d %X'     # ISO时间标准
    if not Timeformat:
        Timeformat = __ISOTIMEFORMAT
    __now_time_str = time.strftime(Timeformat, time.gmtime(time.time()))

    if returnType.find('datetime') != -1:
        return datetime.datetime.strptime(__now_time_str, Timeformat)
    else:
        return __now_time_str 
Example 3
Source File: common.py    From inter with SIL Open Font License 1.1 6 votes vote down vote up
def getLocalTimeZoneOffset():  # in seconds from UTC
  # seriously ugly hack to get timezone offset in Python
  global _local_tz_offs
  if _local_tz_offs is None:
    tzname = time.strftime("%Z", time.localtime())
    s = time.strftime('%z', time.strptime(tzname, '%Z'))
    i = 0
    neg = False
    if s[0] == '-':
      neg = True
      i = 1
    elif s[0] == '+':
      i = 1
    h = int(s[i:i+2])
    m = int(s[i+2:])
    _local_tz_offs = ((h * 60) + m) * 60
    if neg:
      _local_tz_offs = -_local_tz_offs
  return _local_tz_offs


# update environment to include $VENVDIR/bin 
Example 4
Source File: datetime_utils.py    From django-htk with MIT License 6 votes vote down vote up
def get_timezones_within_current_local_time_bounds(start_hour, end_hour, isoweekdays=None):
    """Get a list of all timezone names whose current local time is within `start_hour` and `end_hour`

    If `isoweekdays` specified, also checks that it falls on one of the days of the week (Monday = 1, Sunday = 7)

    `start_hour` and `end_hour` are naive times
    """
    all_timezones = pytz.all_timezones
    timezone_names = []
    now = utcnow()
    def _is_within_time_bounds(tz_name):
        tz = pytz.timezone(tz_name)
        tz_datetime = now.astimezone(tz)
        result = start_hour <= tz_datetime.hour < end_hour and (isoweekdays is None or now.isoweekday() in isoweekdays)
        return result
    timezone_names = filter(_is_within_time_bounds, all_timezones)
    return timezone_names 
Example 5
Source File: lookup.py    From django-htk with MIT License 6 votes vote down vote up
def get_users_currently_at_local_time(start_hour, end_hour, isoweekdays=None, active=True):
    """Returns a Queryset of Users whose current local time is within a time range

    `start_hour` and `end_hour` are naive datetimes
    If `isoweekdays` is specified, also checks that it falls on one of the days of the week (Monday = 1, Sunday = 7)
    """
    timezones = get_timezones_within_current_local_time_bounds(start_hour, end_hour, isoweekdays=isoweekdays)
    UserModel = get_user_model()
    users = _filters.users_currently_at_local_time(
        UserModel.objects,
        start_hour,
        end_hour,
        isoweekdays=isoweekdays
    )

    if active is not None:
        users = _filters.active_users(users, active=active)
    return users 
Example 6
Source File: telltime.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getLocalTime(date, time, *args, **kwargs):
    """
    Get the time in the local timezone from date and time
    """
    if time is not None:
        return getLocalDateAndTime(date, time, *args, **kwargs)[1] 
Example 7
Source File: telltime.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getLocalTimeAtDate(atDate, time, *args, **kwargs):
    """
    Get the time at a certain date in the local timezone
    """
    if time is not None:
        # I don't know what date to use to get the correct atDate, so
        # try all the possibilities until we get it.
        for offset in (0, 1, -1, 2, -2):
            date = atDate + dt.timedelta(days=offset)
            retval = getLocalDateAndTime(date, time, *args, **kwargs)
            if retval[0] == atDate:
                return retval[1] 
Example 8
Source File: telltime.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getLocalDateAndTime(date, time, *args, **kwargs):
    """
    Get the date and time in the local timezone from date and optionally time
    """
    localDt = getLocalDatetime(date, time, *args, **kwargs)
    if time is not None:
        return (localDt.date(), localDt.timetz())
    else:
        return (localDt.date(), None) 
Example 9
Source File: utils.py    From aws-elastic-beanstalk-cli with Apache License 2.0 5 votes vote down vote up
def get_local_time(utctime):
    if isinstance(utctime, str):
        utctime = parser.parse(utctime)

    from_zone = tz.tzutc()
    to_zone = tz.tzlocal()
    utctime = utctime.replace(tzinfo=from_zone)
    return utctime.astimezone(to_zone) 
Example 10
Source File: stalk.py    From git-stalk-cli with MIT License 5 votes vote down vote up
def get_local_time(string):
    """Returns the local time."""
    local_time = convert_to_local(string)
    tukde = local_time.split(' ')
    samay = tukde[1].split('+')[0]

    return samay 
Example 11
Source File: local_server_time.py    From baobab.lims with GNU General Public License v3.0 5 votes vote down vote up
def getLocalServerTime(datetime_object):
    sliced_time = str(datetime_object)[:16]
    new_time = sliced_time + ' ' + getTimeZoneOffset()

    return new_time 
Example 12
Source File: config_geo_pubsub_pull.py    From bigquery-reverse-geolocation with Apache License 2.0 5 votes vote down vote up
def get_local_time(timezone_response):
    # get offset from UTC
    rawOffset = float(timezone_response["rawOffset"])
    # get any daylight savings offset
    dstOffset = float(timezone_response["dstOffset"])

    # combine for total offset from UTC
    return rawOffset + dstOffset

# [START maininit] 
Example 13
Source File: models.py    From django-htk with MIT License 5 votes vote down vote up
def get_local_time(self, dt=None):
        """Gets the current local time for User
        If `dt` is specified, format `dt` into User's timezone
        """
        tz = self.get_django_timezone()
        if dt is None:
            local_time = utcnow().astimezone(tz)
        else:
            local_time = dt.astimezone(tz)
        return local_time 
Example 14
Source File: suntime.py    From suntime with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_local_sunset_time(self, date=None, local_time_zone=tz.tzlocal()):
        """
        Get sunset time for local or custom time zone.
        :param date: Reference date
        :param local_time_zone: Local or custom time zone.
        :return: Local time zone sunset datetime
        """
        date = datetime.date.today() if date is None else date
        ss = self._calc_sun_time(date, False)
        if ss is None:
            raise SunTimeException('The sun never sets on this location (on the specified date)')
        else:
            return ss.astimezone(local_time_zone) 
Example 15
Source File: suntime.py    From suntime with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_local_sunrise_time(self, date=None, local_time_zone=tz.tzlocal()):
        """
        Get sunrise time for local or custom time zone.
        :param date: Reference date. Today if not provided.
        :param local_time_zone: Local or custom time zone.
        :return: Local time zone sunrise datetime
        """
        date = datetime.date.today() if date is None else date
        sr = self._calc_sun_time(date, True)
        if sr is None:
            raise SunTimeException('The sun never rises on this location (on the specified date)')
        else:
            return sr.astimezone(local_time_zone) 
Example 16
Source File: igd_time.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def GetLocalTimeZoneName(self):
    try:
      return open(self.tzfile, 'r').readline().strip()
    except IOError:
      return'' 
Example 17
Source File: default.py    From kodi with GNU General Public License v3.0 5 votes vote down vote up
def getLocalTime(self, epgstart, epgend):
        current = False
        duration = 0
        epgformat = u'%Y-%m-%d %H:%M:%S'
        time_ = datetime.datetime(*(time.strptime(epgstart, epgformat)[:6])) + datetime.timedelta(hours = self.time_zone)
        timeend = datetime.datetime(*(time.strptime(epgend, epgformat)[:6])) + datetime.timedelta(hours = self.time_zone)
        epgtoday = datetime.datetime.today()
        duration = (timeend - epgtoday).seconds
        epgcolor = "FFFFFFFF"
        if epgtoday > timeend:
            epgcolor = "55FFFFFF"
        if (epgtoday >= time_) and (epgtoday < timeend):
            epgcolor = "FF00FF00"
            current = True            
        return '{:%H:%M}'.format(time_), epgcolor, current, duration 
Example 18
Source File: adafruit_pyportal.py    From Adafruit_CircuitPython_PyPortal with MIT License 4 votes vote down vote up
def get_local_time(self, location=None):
        # pylint: disable=line-too-long
        """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.

        :param str location: Your city and country, e.g. ``"New York, US"``.

        """
        # pylint: enable=line-too-long
        self._connect_esp()
        api_url = None
        try:
            aio_username = secrets["aio_username"]
            aio_key = secrets["aio_key"]
        except KeyError:
            raise KeyError(
                "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'"  # pylint: disable=line-too-long
            )

        location = secrets.get("timezone", location)
        if location:
            print("Getting time for timezone", location)
            api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
        else:  # we'll try to figure it out from the IP address
            print("Getting time from IP address")
            api_url = TIME_SERVICE % (aio_username, aio_key)
        api_url += TIME_SERVICE_STRFTIME
        try:
            response = requests.get(api_url, timeout=10)
            if response.status_code != 200:
                raise ValueError(response.text)
            if self._debug:
                print("Time request: ", api_url)
                print("Time reply: ", response.text)
            times = response.text.split(" ")
            the_date = times[0]
            the_time = times[1]
            year_day = int(times[2])
            week_day = int(times[3])
            is_dst = None  # no way to know yet
        except KeyError:
            raise KeyError(
                "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones"  # pylint: disable=line-too-long
            )
        year, month, mday = [int(x) for x in the_date.split("-")]
        the_time = the_time.split(".")[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(":")]
        now = time.struct_time(
            (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
        )
        print(now)
        rtc.RTC().datetime = now

        # now clean up
        response.close()
        response = None
        gc.collect()