query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
how to get current date
python
def now_date(str=False): """Get the current date.""" if str: return datetime.datetime.now().strftime("%Y-%m-%d") return datetime.date.today()
https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L86-L90
how to get current date
python
def get_current_date_time(i): """ Input: {} Output: { return - return code = 0 array - array with date and time iso_datetime - date and time in ISO format } """ import datetime a={} now1=datetime.datetime.now() now=now1.timetuple() a['date_year']=now[0] a['date_month']=now[1] a['date_day']=now[2] a['time_hour']=now[3] a['time_minute']=now[4] a['time_second']=now[5] return {'return':0, 'array':a, 'iso_datetime':now1.isoformat()}
https://github.com/ctuning/ck/blob/7e009814e975f8742790d3106340088a46223714/ck/kernel.py#L4351-L4377
how to get current date
python
def setCurrentDate( self, date ): """ Sets the current date displayed by this calendar widget. :return <QDate> """ if ( date == self._currentDate or not date.isValid() ): return self._currentDate = date self.markForRebuild() parent = self.parent() if ( not parent.signalsBlocked() ): parent.currentDateChanged.emit(date) parent.titleChanged.emit(self.title())
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendarscene.py#L538-L553
how to get current date
python
def now_time(str=False): """Get the current time.""" if str: return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return datetime.datetime.now()
https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/pyhottop.py#L79-L83
how to get current date
python
def get_timestamp(dt=None): ''' Return current timestamp if @dt is None else return timestamp of @dt. >>> t = datetime.datetime(2015, 0o5, 21) >>> get_timestamp(t) 1432166400 ''' if dt is None: dt = datetime.datetime.utcnow() t = dt.utctimetuple() return calendar.timegm(t)
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/misc.py#L33-L46
how to get current date
python
def get_date(date): """ Get the date from a value that could be a date object or a string. :param date: The date object or string. :returns: The date object. """ if type(date) is str: return datetime.strptime(date, '%Y-%m-%d').date() else: return date
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/core/helpers.py#L23-L34
how to get current date
python
def get_30_date(): """ 获得用于查询的默认日期, 今天的日期, 以及30天前的日期 用于查询的日期格式通常为 20160211 :return: """ now = datetime.datetime.now() end_date = now.date() start_date = end_date - datetime.timedelta(days=30) return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d")
https://github.com/shidenggui/easytrader/blob/e5ae4daeda4ea125763a95b280dd694c7f68257d/easytrader/helpers.py#L142-L151
how to get current date
python
def getDate(self): "returns the GMT response datetime or None" date = self.headers.get('date') if date: date = self.convertTimeString(date) return date
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/cache/__init__.py#L75-L80
how to get current date
python
def current_timestamp(self) -> datetime: """Get the current state timestamp.""" timestamp = DB.get_hash_value(self._key, 'current_timestamp') return datetime_from_isoformat(timestamp)
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/execution_control/configuration_db/sip_config_db/states/_state_object.py#L93-L96
how to get current date
python
def get_date(): ''' Displays the current date :return: the system date :rtype: str CLI Example: .. code-block:: bash salt '*' timezone.get_date ''' ret = salt.utils.mac_utils.execute_return_result('systemsetup -getdate') return salt.utils.mac_utils.parse_return(ret)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L61-L75
how to get current date
python
def next_date(self): """ Date when this event is next scheduled to occur in the local time zone (Does not include postponements, but does exclude cancellations) """ nextDt = self.__localAfter(timezone.localtime(), dt.time.min) if nextDt is not None: return nextDt.date()
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L951-L958
how to get current date
python
def get_current_time(self): """ Get current time :return: datetime.time """ hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)] return datetime.time(*hms)
https://github.com/centralniak/py-raildriver/blob/c7f5f551e0436451b9507fc63a62e49a229282b9/raildriver/library.py#L134-L141
how to get current date
python
def get_date(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() month = self.get_month() day = self.get_day() return _date_from_string(year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format())
https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/views.py#L343-L353
how to get current date
python
def current_time(self) -> datetime: """Extract current time.""" _date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d") _time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M") return datetime.combine(_date.date(), _time.time())
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L146-L150
how to get current date
python
def get_current(self): """Get current forecast.""" now = dt.now().timestamp() url = build_url(self.api_key, self.spot_id, self.fields, self.unit, now, now) return get_msw(url)
https://github.com/jcconnell/python-magicseaweed/blob/b22d5f22a134532ac6ab7fc274ee768e85f624a0/magicseaweed/__init__.py#L164-L169
how to get current date
python
def get_future_days(self): """Return only future Day objects.""" today = timezone.now().date() return Day.objects.filter(date__gte=today)
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/schedule/models.py#L108-L112
how to get current date
python
def get_date(self, p_tag): """ Given a date tag, return a date object. """ string = self.tag_value(p_tag) result = None try: result = date_string_to_date(string) if string else None except ValueError: pass return result
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Todo.py#L38-L48
how to get current date
python
def nextday(self): ''' nextday: 下一個日期 :rtype: datetime :returns: 下一個預設時間日期 ''' nextday = self.__zero.date() + timedelta(days=1) return datetime.combine(nextday, time())
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/tw_time.py#L85-L92
how to get current date
python
def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. And defines self.year/month/day for EntryQuerysetArchiveTemplateResponseMixin. """ now = timezone.now() if timezone.is_aware(now): now = timezone.localtime(now) today = now.date() self.year, self.month, self.day = today.isoformat().split('-') return self._get_dated_items(today)
https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/views/archives.py#L97-L108
how to get current date
python
def get_date_yyyymmdd(yyyymmdd): """Return datetime.date given string.""" return date(int(yyyymmdd[:4]), int(yyyymmdd[4:6], base=10), int(yyyymmdd[6:], base=10))
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/anno/annoreader_base.py#L139-L141
how to get current date
python
def today(self): """Return the Day for the current day""" today = timezone.now().date() try: return Day.objects.get(date=today) except Day.DoesNotExist: return None
https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/schedule/models.py#L114-L120
how to get current date
python
def __get_current_datetime(self): """Get current datetime for every file.""" self.wql_time = "SELECT LocalDateTime FROM Win32_OperatingSystem" self.current_time = self.query(self.wql_time) # [{'LocalDateTime': '20160824161431.977000+480'}]' self.current_time_string = str( self.current_time[0].get('LocalDateTime').split('.')[0]) # '20160824161431' self.current_time_format = datetime.datetime.strptime( self.current_time_string, '%Y%m%d%H%M%S') # param: datetime.datetime(2016, 8, 24, 16, 14, 31) -> type: # datetime.datetime return self.current_time_format
https://github.com/crazy-canux/arguspy/blob/e9486b5df61978a990d56bf43de35f3a4cdefcc3/scripts/check_wmi_sh.py#L226-L238
how to get current date
python
def parse_dates(d, default='today'): """ Parses one or more dates from d """ if default == 'today': default = datetime.datetime.today() if d is None: return default elif isinstance(d, _parsed_date_types): return d elif is_number(d): # Treat as milliseconds since 1970 d = d if isinstance(d, float) else float(d) return datetime.datetime.utcfromtimestamp(d) elif not isinstance(d, STRING_TYPES): if hasattr(d, '__iter__'): return [parse_dates(s, default) for s in d] else: return default elif len(d) == 0: # Behaves like dateutil.parser < version 2.5 return default else: try: return parser.parse(d) except (AttributeError, ValueError): return default
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/dates.py#L9-L40
how to get current date
python
def _get_next_date_from_partial_date(partial_date): """Calculates the next date from the given partial date. Args: partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated. Returns: PartialDate: The next date from the given partial date. """ relativedelta_arg = 'years' if partial_date.month: relativedelta_arg = 'months' if partial_date.day: relativedelta_arg = 'days' next_date = parse(partial_date.dumps()) + relativedelta(**{relativedelta_arg: 1}) return PartialDate.from_parts( next_date.year, next_date.month if partial_date.month else None, next_date.day if partial_date.day else None )
https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/utils/visitor_utils.py#L282-L303
how to get current date
python
def get_now(): """ Allows to access global request and read a timestamp from query. """ if not get_current_request: return datetime.datetime.now() request = get_current_request() if request: openinghours_now = request.GET.get('openinghours-now') if openinghours_now: return datetime.datetime.strptime(openinghours_now, '%Y%m%d%H%M%S') return datetime.datetime.now()
https://github.com/arteria/django-openinghours/blob/6bad47509a14d65a3a5a08777455f4cc8b4961fa/openinghours/utils.py#L33-L44
how to get current date
python
def get_date(cls, name): """ Checks a string for a possible date formatted into the name. It assumes dates do not have other numbers at the front or head of the date. Currently only supports dates in 1900 and 2000. Heavily relies on datetime for error checking to see if date is actually viable. It follows similar ideas to this post: http://stackoverflow.com/questions/9978534/match-dates-using-python-regular-expressions :param name: str, string that represents a possible name of an object :return: datetime.datetime, datetime object with current time or None if not found """ time_formats = ['%Y-%m-%d_%H-%M-%S', '%Y-%m-%d-%H-%M-%S', '%Y-%m-%d--%H-%M-%S', '%y_%m_%dT%H_%M_%S', '%Y-%m-%d%H-%M-%S', '%Y%m%d-%H%M%S', '%Y%m%d-%H%M', '%Y-%m-%d', '%Y%m%d', '%m_%d_%Y', '%m_%d_%y', '%m%d%y', '%m%d%Y', '%d_%m_%Y', '%Y', '%m-%d-%yy', '%m%d%Y'] mapping = [('%yy', '(([01]\d{1}))'), ('%Y', '((19|20)\d{2})'), ('%y', '(\d{2})'), ('%d', '(\d{2})'), ('%m', '(\d{2})'), ('%H', '(\d{2})'), ('%M', '(\d{2})'), ('%S', '(\d{2})')] time_regexes = [] for time_format in time_formats: for k, v in mapping: time_format = time_format.replace(k, v) time_regexes.append(time_format) for time_regex, time_format in zip(time_regexes, time_formats): match = cls._get_regex_search(name, cls.REGEX_DATE % time_regex, metadata={'format': time_format}, match_index=0) if match: try: match.update({ 'datetime': datetime.datetime.strptime(match['match'], time_format.replace('%yy', '%y')) }) return match except ValueError: pass return None
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/nameparser.py#L185-L235
how to get current date
python
def check_date (self): """ Check for special dates. """ now = datetime.date.today() if now.day == 7 and now.month == 1: msg = _("Happy birthday for LinkChecker, I'm %d years old today!") self.comment(msg % (now.year - 2000))
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/__init__.py#L273-L280
how to get current date
python
def get_current_observation_date(self): """ Get the date of the current observation by looking in the header of the observation for the DATE and EXPTIME keywords. The 'DATE AT MIDDLE OF OBSERVATION' of the observation is returned @return: Time """ # All HDU elements have the same date and time so just use # last one, sometimes the first one is missing the header, in MEF header = self.get_current_cutout().hdulist[-1].header mjd_obs = float(header.get('MJD-OBS')) exptime = float(header.get('EXPTIME')) mpc_date = Time(mjd_obs, format='mjd', scale='utc', precision=config.read('MPC.DATE_PRECISION')) mpc_date += TimeDelta(exptime * units.second) / 2.0 mpc_date = mpc_date.mpc return mpc_date
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/models/validation.py#L222-L241
how to get current date
python
def time_ago_to_date(value): """ Parse a date and return it as ``datetime.date`` objects. Examples of valid dates: * Relative: 2 days ago, today, yesterday, 1 week ago * Absolute: 25.10.2017 """ today = datetime.date.today() if value == 'today': return today elif value == 'yesterday': return today - datetime.timedelta(days=1) time_ago = re.match(r'(\d+) (days?|weeks?|months?|years?) ago', value) if time_ago: duration, unit = int(time_ago.group(1)), time_ago.group(2) if 'day' in unit: return today - datetime.timedelta(days=duration) elif 'week' in unit: return today - datetime.timedelta(weeks=duration) elif 'month' in unit: return months_ago(today, duration) elif 'year' in unit: return today.replace(year=today.year - duration) return datetime.datetime.strptime(value, '%d.%m.%Y').date()
https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/utils/date.py#L52-L80
how to get current date
python
def get_dates_in_period(start=None, top=None, step=1, step_dict={}): """Return a list of dates from the `start` to `top`.""" delta = relativedelta(**step_dict) if step_dict else timedelta(days=step) start = start or datetime.today() top = top or start + delta dates = [] current = start while current <= top: dates.append(current) current += delta return dates
https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L30-L42
how to get current date
python
def date(self): """DATE command. Coordinated Universal time from the perspective of the usenet server. It can be used to provide information that might be useful when using the NEWNEWS command. See <http://tools.ietf.org/html/rfc3977#section-7.1> Returns: The UTC time according to the server as a datetime object. Raises: NNTPDataError: If the timestamp can't be parsed. """ code, message = self.command("DATE") if code != 111: raise NNTPReplyError(code, message) ts = date.datetimeobj(message, fmt="%Y%m%d%H%M%S") return ts
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L570-L591
how to get current date
python
def get_next(weekday, including_today=False): """Gets next day of week :param weekday: day of week :param including_today: If today is sunday and requesting next sunday :return: Date of next monday, tuesday .. """ now = datetime.datetime.now() if now.weekday() == weekday.value and including_today: delta = datetime.timedelta(days=0) elif now.weekday() == weekday.value and not including_today: delta = datetime.timedelta(days=7) else: delta = datetime.timedelta( (7 + weekday.value - now.weekday()) % 7 ) # times delta to next instance return Day(now + delta).get_just_date()
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L21-L37
how to get current date
python
def prev_date(self): """ Date when this event last occurred in the local time zone (Does not include postponements, but does exclude cancellations) """ prevDt = self.__localBefore(timezone.localtime(), dt.time.min) if prevDt is not None: return prevDt.date()
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L972-L979
how to get current date
python
def days_ago(n, hour=0, minute=0, second=0, microsecond=0): """ Get a datetime object representing `n` days ago. By default the time is set to midnight. """ today = timezone.utcnow().replace( hour=hour, minute=minute, second=second, microsecond=microsecond) return today - timedelta(days=n)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dates.py#L227-L237
how to get current date
python
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L64-L70
how to get current date
python
def getDate(): """Returns a formatted string with the current date.""" _ltime = _time.localtime(_time.time()) date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return date_str
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L162-L168
how to get current date
python
def get_recent_mtime(t): '''获取更精简的时间. 如果是当天的, 就返回时间; 如果是当年的, 就近回月份和日期; 否则返回完整的时间 ''' if isinstance(t, int): # ignore micro seconds if len(str(t)) == 13: t = t // 1000 t = datetime.datetime.fromtimestamp(t) now = datetime.datetime.now() delta = now - t if delta.days == 0: return datetime.datetime.strftime(t, '%H:%M:%S') elif now.year == t.year: return datetime.datetime.strftime(t, '%b %d') else: return datetime.datetime.strftime(t, '%b %d %Y')
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/util.py#L79-L96
how to get current date
python
def now(utc=False, tz=None): """ Get a current DateTime object. By default is local. .. code:: python reusables.now() # DateTime(2016, 12, 8, 22, 5, 2, 517000) reusables.now().format("It's {24-hour}:{min}") # "It's 22:05" :param utc: bool, default False, UTC time not local :param tz: TimeZone as specified by the datetime module :return: reusables.DateTime """ return datetime.datetime.utcnow() if utc else datetime.datetime.now(tz=tz)
https://github.com/cdgriffith/Reusables/blob/bc32f72e4baee7d76a6d58b88fcb23dd635155cd/reusables/dt.py#L100-L116
how to get current date
python
def _next_year(): """Get the date of today plus one year. :rtype: str :returns: The date of this day next year, in the format '%Y-%m-%d'. """ now = datetime.now().__str__() date = now.split(' ', 1)[0] year, month, day = date.split('-', 2) next_year = str(int(year)+1) return '-'.join((next_year, month, day))
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L633-L643
how to get current date
python
def past_datetime(self, start_date='-30d', tzinfo=None): """ Get a DateTime object based on a random date between a given date and 1 second ago. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to "-30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date=start_date, end_date='-1s', tzinfo=tzinfo, )
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1617-L1630
how to get current date
python
def parse_date(self, item, field_name, source_name): """ Converts the date in the format: Thu 03. As only the day is provided, tries to find the best match based on the current date, considering that dates are on the past. """ # Get the current date now = datetime.now().date() # Get the date from the source val = self.get_value(item, source_name) week_day, day = val.split() day = int(day) # If the current date is minor than the item date # go back one month if now.day < day: if now.month == 1: now = now.replace(month=12, year=now.year-1) else: now = now.replace(month=now.month-1) # Finally, replace the source day in the current date # and return now = now.replace(day=day) return now
https://github.com/ricobl/django-importer/blob/6967adfa7a286be7aaf59d3f33c6637270bd9df6/sample_project/tasks/importers.py#L64-L88
how to get current date
python
def get_api_date(self): ''' Figure out the date to use for API requests. Assumes yesterday's date if between midnight and 10am Eastern time. Override this function in a subclass to change how the API date is calculated. ''' # NOTE: If you are writing your own function to get the date, make sure # to include the first if block below to allow for the ``date`` # parameter to hard-code a date. api_date = None if self.date is not None and not isinstance(self.date, datetime): try: api_date = datetime.strptime(self.date, '%Y-%m-%d') except (TypeError, ValueError): self.logger.warning('Invalid date \'%s\'', self.date) if api_date is None: utc_time = pytz.utc.localize(datetime.utcnow()) eastern = pytz.timezone('US/Eastern') api_date = eastern.normalize(utc_time.astimezone(eastern)) if api_date.hour < 10: # The scores on NHL.com change at 10am Eastern, if it's before # that time of day then we will use yesterday's date. api_date -= timedelta(days=1) self.date = api_date
https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/scores/__init__.py#L83-L107
how to get current date
python
def getCurrentStrDatetime(): """ Generating the current Datetime with a given format Returns: -------- string: The string of a date. """ # Generating current time i = datetime.datetime.now() strTime = "%s-%s-%s_%sh%sm" % (i.year, i.month, i.day, i.hour, i.minute) return strTime
https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/general.py#L671-L682
how to get current date
python
def getDateFromToday(delta,strfmt='%Y%m%d'): """ Returns a string that represents a date n numbers of days from today. Parameters: ----------- delta : int number of days strfmt : string format in which the date will be represented """ return (dt.date.today() + dt.timedelta(delta)).strftime(strfmt)
https://github.com/santosjorge/cufflinks/blob/ca1cbf93998dc793d0b1f8ac30fe1f2bd105f63a/cufflinks/date_tools.py#L9-L18
how to get current date
python
def get_timestamp_at(time_in=None, time_at=None): ''' Computes the timestamp for a future event that may occur in ``time_in`` time or at ``time_at``. ''' if time_in: if isinstance(time_in, int): hours = 0 minutes = time_in else: time_in = time_in.replace('h', ':') time_in = time_in.replace('m', '') try: hours, minutes = time_in.split(':') except ValueError: hours = 0 minutes = time_in if not minutes: minutes = 0 hours, minutes = int(hours), int(minutes) dt = timedelta(hours=hours, minutes=minutes) time_now = datetime.utcnow() time_at = time_now + dt return time.mktime(time_at.timetuple()) elif time_at: log.debug('Predicted at specified as %s', time_at) if isinstance(time_at, (six.integer_types, float)): # then it's a timestamp return time_at else: fmts = ('%H%M', '%Hh%M', '%I%p', '%I:%M%p', '%I:%M %p') # Support different formats for the timestamp # The current formats accepted are the following: # # - 18:30 (and 18h30) # - 1pm (no minutes, fixed hour) # - 1:20am (and 1:20am - with or without space) for fmt in fmts: try: log.debug('Trying to match %s', fmt) dt = datetime.strptime(time_at, fmt) return time.mktime(dt.timetuple()) except ValueError: log.debug('Did not match %s, continue searching', fmt) continue msg = '{pat} does not match any of the accepted formats: {fmts}'.format(pat=time_at, fmts=', '.join(fmts)) log.error(msg) raise ValueError(msg)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeutil.py#L18-L66
how to get current date
python
def Timestamp(): """ Get the current datetime in UTC """ timestamp = '' try: timestamp = str(datetime.datetime.now())+' UTC' except Exception as e: # pragma: no cover logger.error('Could not get current time ' + str(e)) return timestamp
https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L653-L660
how to get current date
python
def yesterday(self) -> datetime: """ Set the value to yesterday """ self.value = datetime.today() - timedelta(days=1) return self.value
https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L218-L221
how to get current date
python
def date_this_year(self, before_today=True, after_today=False): """ Gets a Date object for the current year. :param before_today: include days in current year before today :param after_today: include days in current year after today :example Date('2012-04-04') :return Date """ today = date.today() this_year_start = today.replace(month=1, day=1) next_year_start = date(today.year + 1, 1, 1) if before_today and after_today: return self.date_between_dates(this_year_start, next_year_start) elif not before_today and after_today: return self.date_between_dates(today, next_year_start) elif not after_today and before_today: return self.date_between_dates(this_year_start, today) else: return today
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1859-L1879
how to get current date
python
def _get_date(day=None, month=None, year=None): """Returns a datetime object with optional params or today.""" now = datetime.date.today() if day is None: return now try: return datetime.date( day=int(day), month=int(month or now.month), year=int(year or now.year), ) except ValueError as error: print("error: {0}".format(error), file=sys.stderr)
https://github.com/a-tal/ddate/blob/3cb4f510e0b7c33e1a3732c4c7b4817629ab733c/ddate/base.py#L196-L210
how to get current date
python
def get_upcoming_events(self, days_to_look_ahead): '''Returns the events from the calendar for the next days_to_look_ahead days.''' now = datetime.now(tz=self.timezone) # timezone? start_time = datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second, tzinfo=self.timezone) end_time = start_time + timedelta(days = days_to_look_ahead) start_time = start_time.isoformat() end_time = end_time.isoformat() return self.get_events(start_time, end_time)
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/google/gcalendar.py#L296-L303
how to get current date
python
def prevmonday(num): """ Return unix SECOND timestamp of "num" mondays ago """ today = get_today() lastmonday = today - timedelta(days=today.weekday(), weeks=num) return lastmonday
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/dashboards/sitedash/app.py#L74-L80
how to get current date
python
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L69-L72
how to get current date
python
def date_this_month(self, before_today=True, after_today=False): """ Gets a Date object for the current month. :param before_today: include days in current month before today :param after_today: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return DateTime """ today = date.today() this_month_start = today.replace(day=1) next_month_start = this_month_start + \ relativedelta.relativedelta(months=1) if before_today and after_today: return self.date_between_dates(this_month_start, next_month_start) elif not before_today and after_today: return self.date_between_dates(today, next_month_start) elif not after_today and before_today: return self.date_between_dates(this_month_start, today) else: return today
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1881-L1903
how to get current date
python
def get_upcoming_events_within_the_current_week(self): '''Returns the events from the calendar for the next days_to_look_ahead days.''' now = datetime.now(tz=self.timezone) # timezone? start_time = datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second, tzinfo=self.timezone) end_time = start_time + timedelta(days = 6 - now.weekday()) end_time = datetime(year = end_time.year, month = end_time.month, day = end_time.day, hour=23, minute=59, second=59, tzinfo=self.timezone) assert(end_time.weekday() == 6) start_time = start_time.isoformat() end_time = end_time.isoformat() return self.get_events(start_time, end_time)
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/google/gcalendar.py#L280-L289
how to get current date
python
def date(self, pattern='%Y-%m-%d', end_datetime=None): """ Get a date string between January 1, 1970 and now :param pattern format :example '2008-11-27' """ return self.date_time(end_datetime=end_datetime).strftime(pattern)
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1436-L1442
how to get current date
python
def filter_pastdate(string, default=None): """Coerce to a date not beyond the current date If only a day is given, assumes the current month if that day has passed or is the current day, otherwise assumes the previous month. If a day and month are given, but no year, assumes the current year if the given date has passed (or is today), otherwise the previous year. """ if not string and default is not None: return default today = datetime.date.today() # split the string try: parts = map(int, re.split('\D+', string)) # split the string except ValueError: raise InvalidInputError("invalid date; use format: DD [MM [YYYY]]") if len(parts) < 1 or len(parts) > 3: raise InvalidInputError("invalid date; use format: DD [MM [YYYY]]") if len(parts) == 1: # no month or year given; append month parts.append(today.month - 1 if parts[0] > today.day else today.month) if parts[1] < 1: parts[1] = 12 if len(parts) == 2: # no year given; append year if parts[1] > today.month \ or parts[1] == today.month and parts[0] > today.day: parts.append(today.year - 1) else: parts.append(today.year) parts.reverse() try: date = datetime.date(*parts) if date > today: raise InvalidInputError("cannot choose a date in the future") return date except ValueError: print parts raise InvalidInputError("invalid date; use format: DD [MM [YYYY]]")
https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/ui.py#L102-L148
how to get current date
python
def _next_month(self): """Update calendar to show the next month.""" self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3112-L3120
how to get current date
python
def future_datetime(self, end_date='+30d', tzinfo=None): """ Get a DateTime object based on a random date between 1 second form now and a given date. Accepts date strings that can be recognized by strtotime(). :param end_date Defaults to "+30d" :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('1999-02-02 11:42:52') :return DateTime """ return self.date_time_between( start_date='+1s', end_date=end_date, tzinfo=tzinfo, )
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1589-L1602
how to get current date
python
def past_date(start='-30d'): """ Returns a ``date`` object in the past between 1 day ago and the specified ``start``. ``start`` can be a string, another date, or a timedelta. If it's a string, it must start with `-`, followed by and integer and a unit, Eg: ``'-30d'``. Defaults to `'-30d'` Valid units are: * ``'years'``, ``'y'`` * ``'weeks'``, ``'w'`` * ``'days'``, ``'d'`` * ``'hours'``, ``'h'`` * ``'minutes'``, ``'m'`` * ``'seconds'``, ``'s'`` """ return lambda n, f: f.past_date( start_date=start, tzinfo=get_timezone(), )
https://github.com/fcurella/django-fakery/blob/05b6d6a9bf4b8fab98bf91fe1dce5a812d951987/django_fakery/shortcuts.py#L69-L86
how to get current date
python
def previous_day(self): """Return the HDate for the previous day.""" return HDate(self.gdate + datetime.timedelta(-1), self.diaspora, self.hebrew)
https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/date.py#L243-L246
how to get current date
python
def updated(self): 'return datetime.datetime' return dateutil.parser.parse(str(self.f.latestRevision.updated))
https://github.com/havardgulldahl/jottalib/blob/4d015e4309b1d9055e561ec757363fb2632b4eb7/src/jottalib/JFS.py#L461-L463
how to get current date
python
def __loaddate(): ''' 載入檔案 檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php ''' csv_path = os.path.join(os.path.dirname(__file__), 'opendate.csv') with open(csv_path) as csv_file: csv_data = csv.reader(csv_file) result = {} result['close'] = [] result['open'] = [] for i in csv_data: if i[1] == '0': # 0 = 休市 result['close'].append(datetime.strptime(i[0], '%Y/%m/%d').date()) elif i[1] == '1': # 1 = 開市 result['open'].append(datetime.strptime(i[0], '%Y/%m/%d').date()) else: pass return result
https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/twseopen.py#L52-L71
how to get current date
python
def get_next_weekday(self, including_today=False): """Gets next week day :param including_today: If today is sunday and requesting next sunday :return: Date of next monday, tuesday .. """ weekday = self.date_time.weekday() return Weekday.get_next(weekday, including_today=including_today)
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L122-L129
how to get current date
python
def date_time(self, tzinfo=None, end_datetime=None): """ Get a datetime object for a date between January 1, 1970 and now :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2005-08-16 20:39:21') :return datetime """ # NOTE: On windows, the lowest value you can get from windows is 86400 # on the first day. Known python issue: # https://bugs.python.org/issue30684 return datetime(1970, 1, 1, tzinfo=tzinfo) + \ timedelta(seconds=self.unix_time(end_datetime=end_datetime))
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1389-L1400
how to get current date
python
def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/tseries/holiday.py#L98-L106
how to get current date
python
def get_date(self): """ Collects sensing date of the product. :return: Sensing date :rtype: str """ if self.safe_type == EsaSafeType.OLD_TYPE: name = self.product_id.split('_')[-2] date = [name[1:5], name[5:7], name[7:9]] else: name = self.product_id.split('_')[2] date = [name[:4], name[4:6], name[6:8]] return '-'.join(date_part.lstrip('0') for date_part in date)
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L374-L386
how to get current date
python
def date(objet): """ abstractRender d'une date datetime.date""" if objet: return "{}/{}/{}".format(objet.day, objet.month, objet.year) return ""
https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/Core/formats.py#L250-L254
how to get current date
python
def get_time_now(self): """Returns a time stamp""" import datetime import getpass username = getpass.getuser() # this is not working on some systems: os.environ["USERNAME"] timenow = str(datetime.datetime.now()) timenow = timenow.split('.')[0] msg = '<div class="date">Created on ' + timenow msg += " by " + username +'</div>' return msg
https://github.com/cokelaer/reports/blob/7703b1e27d440c3193ee6cc90bfecd78cc98b737/reports/report.py#L230-L240
how to get current date
python
def getDateTimeFromGet(request,key): ''' This function just parses the request GET data for the requested key, and returns it in datetime format, returning none if the key is not available or is in incorrect format. ''' if request.GET.get(key,''): try: return ensure_timezone(datetime.strptime(unquote(request.GET.get(key,'')),'%Y-%m-%d')) except (ValueError, TypeError): pass return None
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/utils/requests.py#L19-L30
how to get current date
python
def nexttime(self, lastts): ''' Returns next timestamp that meets requirements, incrementing by (self.incunit * incval) if not increasing, or 0.0 if there are no future matches ''' lastdt = datetime.datetime.fromtimestamp(lastts, tz.utc) newvals = {} # all the new fields that will be changed in datetime of lastts # Truncate the seconds part newdt = lastdt.replace(second=0) for unit, newval in self.reqdict.items(): dtkey = _TimeunitToDatetime[unit] if unit is TimeUnit.DAYOFWEEK: newdt = newdt.replace(**newvals) newvals = {} newval = newdt.day + (6 + newval - newdt.weekday()) % 7 + 1 if newval > calendar.monthrange(newdt.year, newdt.month)[1]: newval -= 7 elif unit is TimeUnit.MONTH: # As we change the month, clamp the day of the month to a valid value newdt = newdt.replace(**newvals) newvals = {} dayval = _dayofmonth(newdt.day, newval, newdt.year) newvals['day'] = dayval elif unit is TimeUnit.DAYOFMONTH: newdt = newdt.replace(**newvals) newvals = {} newval = _dayofmonth(newval, newdt.month, newdt.year) newvals[dtkey] = newval newdt = newdt.replace(**newvals) # Then move forward if we have to if newdt <= lastdt or \ self.incunit == TimeUnit.DAYOFWEEK and newdt.weekday() != self.incval: if self.incunit is None: largest_req = min(self.reqdict.keys()) tmpunit = _NextUnitMap[largest_req] if tmpunit is None: # required a year and we're already there return 0.0 # Unless we're going to the next day of week, increment by 1 unit of the next larger unit tmpincval = self.reqdict.get(TimeUnit.DAYOFWEEK, 1) else: tmpunit = self.incunit tmpincval = self.incval newdt = self._inc(tmpunit, tmpincval, self.reqdict, lastdt, newdt) assert newdt > lastdt return newdt.timestamp()
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/agenda.py#L152-L201
how to get current date
python
def get_timestamp(d): """ Returns a UTC timestamp for a C{datetime.datetime} object. @type d: C{datetime.datetime} @return: UTC timestamp. @rtype: C{float} @see: Inspiration taken from the U{Intertwingly blog <http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. """ if isinstance(d, datetime.date) and not isinstance(d, datetime.datetime): d = datetime.datetime.combine(d, datetime.time(0, 0, 0, 0)) msec = str(d.microsecond).rjust(6).replace(' ', '0') return float('%s.%s' % (calendar.timegm(d.utctimetuple()), msec))
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L28-L43
how to get current date
python
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' return datetime.strptime( match.group(), formatter).replace(tzinfo=pytz.UTC)
https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/piwik/core.py#L77-L87
how to get current date
python
def _next_timestamp(self, now, last): """ Returns the timestamp that should be used if ``now`` is the current time and ``last`` is the last timestamp returned by this object. Intended for internal and testing use only; to generate timestamps, call an instantiated ``MonotonicTimestampGenerator`` object. :param int now: an integer to be used as the current time, typically representing the current time in microseconds since the UNIX epoch :param int last: an integer representing the last timestamp returned by this object """ if now > last: self.last = now return now else: self._maybe_warn(now=now) self.last = last + 1 return self.last
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/timestamps.py#L65-L83
how to get current date
python
def GetDate(self): """Retrieves the date represented by the date and time values. Returns: tuple[int, int, int]: year, month, day of month or (None, None, None) if the date and time values do not represent a date. """ if self._timestamp is None: return None, None, None try: number_of_days, _, _, _ = self._GetTimeValues(self._timestamp) return self._GetDateValues(number_of_days, 1970, 1, 1) except ValueError: return None, None, None
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L161-L175
how to get current date
python
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass new_date = date periods = int("".join([s for s in res if s.isdigit()])) if periods > 0: if "K" in res: new_date = date - datetime.timedelta(microseconds=periods) elif "S" in res: new_date = date - datetime.timedelta(seconds=periods) elif "T" in res: new_date = date - datetime.timedelta(minutes=periods) elif "H" in res or "V" in res: new_date = date - datetime.timedelta(hours=periods) elif "W" in res: new_date = date - datetime.timedelta(weeks=periods) else: # days new_date = date - datetime.timedelta(days=periods) # not a week day: while new_date.weekday() > 4: # Mon-Fri are 0-4 new_date = backdate(res="1D", date=new_date, as_datetime=True) if as_datetime: return new_date return new_date.strftime(fmt)
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L375-L414
how to get current date
python
def _get_status_timestamp(row): """Get latest package timestamp.""" try: divs = row.find('div', {'id': 'coltextR3'}).find_all('div') if len(divs) < 2: return None timestamp_string = divs[1].string except AttributeError: return None try: return parse(timestamp_string) except ValueError: return None
https://github.com/happyleavesaoc/python-myusps/blob/827e74f25d1c1ef0149bb7fda7c606297b743c02/myusps/__init__.py#L89-L101
how to get current date
python
def previous_weekday(day=None, as_datetime=False): """ get the most recent business day """ if day is None: day = datetime.datetime.now() else: day = datetime.datetime.strptime(day, '%Y-%m-%d') day -= datetime.timedelta(days=1) while day.weekday() > 4: # Mon-Fri are 0-4 day -= datetime.timedelta(days=1) if as_datetime: return day return day.strftime("%Y-%m-%d")
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L419-L432
how to get current date
python
def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calendar()
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUI27.py#L3104-L3110
how to get current date
python
def _to_date(t): ''' Internal function that tries whatever to convert ``t`` into a :class:`datetime.date` object. >>> _to_date('2013-12-11') datetime.date(2013, 12, 11) >>> _to_date('Wed, 11 Dec 2013') datetime.date(2013, 12, 11) >>> _to_date('Wed, 11 Dec 13') datetime.date(2013, 12, 11) ''' if isinstance(t, six.integer_types + (float, )): return datetime.date.fromtimestamp(t) elif isinstance(t, six.string_types): for date_format in ALL_DATE_FORMATS: try: return datetime.datetime.strptime(t, date_format).date() except ValueError: pass raise ValueError('Format not supported') elif isinstance(t, datetime.datetime): return t.date() elif isinstance(t, datetime.date): return t else: raise TypeError
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L97-L129
how to get current date
python
def currentDateTime(self): """ Returns the current date time for this widget. :return <datetime.datetime> """ view = self.uiGanttVIEW scene = view.scene() point = view.mapToScene(0, 0) return scene.datetimeAt(point.x())
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L300-L309
how to get current date
python
def get_date(date, date_format = None): """Return a datetime object if there is a valid date Raise exception if date is not valid Return todays date if no date where added Args: date(str) date_format(str) Returns: date_obj(datetime.datetime) """ date_obj = datetime.datetime.now() if date: if date_format: date_obj = datetime.datetime.strptime(date, date_format) else: if match_date(date): if len(date.split('-')) == 3: date = date.split('-') elif len(date.split(' ')) == 3: date = date.split(' ') elif len(date.split('.')) == 3: date = date.split('.') else: date = date.split('/') date_obj = datetime.datetime(*(int(number) for number in date)) else: raise ValueError("Date %s is invalid" % date) return date_obj
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/utils/date.py#L19-L50
how to get current date
python
def public_timeline(self, delegate, params={}, extra_args=None): "Get the most recent public timeline." return self.__get('/statuses/public_timeline.atom', delegate, params, extra_args=extra_args)
https://github.com/dustin/twitty-twister/blob/8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3/twittytwister/twitter.py#L367-L371
how to get current date
python
def dateAt(self, x): """ Returns the date at the inputed x position. :return <QDate> """ gantt = self.ganttWidget() dstart = gantt.dateStart() days = int(x / float(gantt.cellWidth())) return dstart.addDays(days)
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttscene.py#L58-L68
how to get current date
python
def current_time(self, date): """ According with API: The time format is "Y-M-D H-m-S". It is not be effected by Locales. TimeFormat in SetLocalesConfig Params: date = "Y-M-D H-m-S" Example: 2016-10-28 13:48:00 Return: True """ ret = self.command( 'global.cgi?action=setCurrentTime&time={0}'.format(date) ) if "ok" in ret.content.decode('utf-8').lower(): return True return False
https://github.com/tchellomello/python-amcrest/blob/ed842139e234de2eaf6ee8fb480214711cde1249/src/amcrest/system.py#L26-L45
how to get current date
python
def get_last_date(self, field, filters_=[]): ''' :field: field with the data :filters_: additional filters to find the date ''' last_date = self.get_last_item_field(field, filters_=filters_) return last_date
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elastic.py#L380-L388
how to get current date
python
def fromNow(offset, dateObj=None): """ Generate a `datetime.datetime` instance which is offset using a string. See the README.md for a full example, but offset could be '1 day' for a datetime object one day in the future """ # We want to handle past dates as well as future future = True offset = offset.lstrip() if offset.startswith('-'): future = False offset = offset[1:].lstrip() if offset.startswith('+'): offset = offset[1:].lstrip() # Parse offset m = r.match(offset) if m is None: raise ValueError("offset string: '%s' does not parse" % offset) # In order to calculate years and months we need to calculate how many days # to offset the offset by, since timedelta only goes as high as weeks days = 0 hours = 0 minutes = 0 seconds = 0 if m.group('years'): years = int(m.group('years')) days += 365 * years if m.group('months'): months = int(m.group('months')) days += 30 * months days += int(m.group('days') or 0) hours += int(m.group('hours') or 0) minutes += int(m.group('minutes') or 0) seconds += int(m.group('seconds') or 0) # Offset datetime from utc delta = datetime.timedelta( weeks=int(m.group('weeks') or 0), days=days, hours=hours, minutes=minutes, seconds=seconds, ) if not dateObj: dateObj = datetime.datetime.utcnow() return dateObj + delta if future else dateObj - delta
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L63-L113
how to get current date
python
def get_date_info(value): """ Returns the datetime object and the format of the date in input :type value: `str` """ fmt = _get_date_format(value) dt_value = _datetime_obj_factory(value, fmt) return dt_value, fmt
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L70-L78
how to get current date
python
def get_expiration_date(self, fn): """ Reads the expiration date of a local crt file. """ r = self.local_renderer r.env.crt_fn = fn with hide('running'): ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True) matches = re.findall('notAfter=(.*?)$', ret, flags=re.IGNORECASE) if matches: return dateutil.parser.parse(matches[0])
https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/ssl.py#L84-L94
how to get current date
python
def getUTCDatetimeDOY(days=0, hours=0, minutes=0, seconds=0): """getUTCDatetimeDOY -> datetime Returns the UTC current datetime with the input timedelta arguments (days, hours, minutes, seconds) added to current date. Returns ISO-8601 datetime format for day of year: YYYY-DDDTHH:mm:ssZ """ return (datetime.datetime.utcnow() + datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)).strftime(DOY_Format)
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dmc.py#L59-L69
how to get current date
python
def reading_dates(reading): """ Given a Reading, with start and end dates and granularities[1] it returns an HTML string representing that period. eg: * '1–6 Feb 2017' * '1 Feb to 3 Mar 2017' * 'Feb 2017 to Mar 2018' * '2017–2018' etc. [1] https://www.flickr.com/services/api/misc.dates.html """ # 3 September 2017 full_format = '<time datetime="%Y-%m-%d">{}</time>'.format('%-d %B %Y') # September 2017 month_year_format = '<time datetime="%Y-%m">{}</time>'.format('%B %Y') # 2017 year_format = '<time datetime="%Y">{}</time>'.format('%Y') # 3 day_format = '<time datetime="%Y-%m-%d">{}</time>'.format('%-d') # 3 September day_month_format = '<time datetime="%Y-%m-%d">{}</time>'.format('%-d %B') # September month_format = '<time datetime="%Y-%m">{}</time>'.format('%B') period_format_short = '{}–{}' period_format_long = '{} to {}' # For brevity: start_date = reading.start_date end_date = reading.end_date start_gran = reading.start_granularity end_gran = reading.end_granularity # Are start and end in the same day, year or month? same_day = False same_month = False same_year = False if start_date and end_date: if start_date.strftime('%Y') == end_date.strftime('%Y'): same_year = True if start_date.strftime('%m%Y') == end_date.strftime('%m%Y'): same_month = True if start_date.strftime('%d%m%Y') == end_date.strftime('%d%m%Y'): same_day = True start_str = '' end_str = '' output = '' # Make some basic start and end strings, which we might use... if start_date: if start_gran == 3: start_str = start_date.strftime(full_format) elif start_gran == 4: start_str = start_date.strftime(month_year_format) else: start_str = start_date.strftime(year_format) if end_date: if end_gran == 3: end_str = end_date.strftime(full_format) elif end_gran == 4: end_str = end_date.strftime(month_year_format) else: end_str = end_date.strftime(year_format) # Now make the final strings we'll return: if start_date and end_date: # A default which will be overridden in many cases. This covers: # 1 February 2017 to 3 March 2018 # 1 February 2017 to March 2018 # 1 February 2017 to 2018 # February 2017 to 3 March 2018 # February 2017 to March 2018 # February 2017 to 2018 # 2017 to 3 March 2018 # 2017 to March 2018 # 2017 to 2018 output = period_format_long.format(start_str, end_str) if (start_gran == 4 or end_gran == 4) and same_month: # Only have enough to output 'February 2017'. output = start_str elif (start_gran == 6 or end_gran == 6) and same_year: # Only have enough to output '2017'. output = start_str elif start_gran == 3: if end_gran == 3: if same_day: # 1 February 2017 output = start_str elif same_month: # 1–6 February 2017 output = period_format_short.format( start_date.strftime(day_format), end_str) elif same_year: # 1 February to 3 March 2017 output = period_format_long.format( start_date.strftime(day_month_format), end_str) elif end_gran == 4: if same_year: # 1 February to March 2017 output = period_format_long.format( start_date.strftime(day_month_format), end_str) elif start_gran == 4: if end_gran == 3: if same_year: # February to 3 March 2017 output = period_format_long.format( start_date.strftime(month_format), end_str) elif end_gran == 4: if same_year: # February to March 2017 output = period_format_long.format( start_date.strftime(month_format), end_str) elif end_date: # Only an end_date. if end_gran == 3: # Finished on 1 February 2017 output = "Finished on {}".format(end_str) else: # Finished in February 2017 # Finished in 2017 output = "Finished in {}".format(end_str) else: # No end_date: the reading has started, but not ended. if start_gran == 3: # Started on 1 February 2017 output = "Started on {}".format(start_str) else: # Started in February 2017 # Started in 2017 output = "Started in {}".format(start_str) return format_html(output)
https://github.com/philgyford/django-spectator/blob/f3c72004f9caa1fde0f5a3b2f0d2bf285fc01ada/spectator/reading/templatetags/spectator_reading.py#L136-L288
how to get current date
python
def working_yesterday(self, date_from=None, date_format=None): """ Retourne la date d'hier depuis maintenant ou depuis une date fournie seulement sur les jours ouvrableq. Ainsi lundi devient samedi et samedi devient vendredi :param: :date_from date de référence :return datetime """ # date d'hier que sur les jours de week-end return self.delta(days=-1, date_from=date_from, date_format=date_format, days_range=[1, 2, 3, 4, 5, 6])
https://github.com/mickbad/mblibs/blob/c1f423ef107c94e2ab6bd253e9148f6056e0ef75/mblibs/fast.py#L921-L931
how to get current date
python
def set_timestamp_to_current(self): """ Set timestamp to current time utc :rtype: None """ # Good form to add tzinfo self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow())
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/message.py#L313-L320
how to get current date
python
def gdate(self): """Return the Gregorian date for the given Hebrew date object.""" if self._last_updated == "gdate": return self._gdate return conv.jdn_to_gdate(self._jdn)
https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/date.py#L117-L121
how to get current date
python
def get_current_ontology_date(): """Get the release date of the current Gene Ontolgo release.""" with closing(requests.get( 'http://geneontology.org/ontology/go-basic.obo', stream=True)) as r: for i, l in enumerate(r.iter_lines(decode_unicode=True)): if i == 1: assert l.split(':')[0] == 'data-version' date = l.split('/')[-1] break return date
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/util.py#L62-L73
how to get current date
python
def get_fc_date(out_config_file): """Retrieve flowcell date, reusing older dates if refreshing a present workflow. """ if os.path.exists(out_config_file): with open(out_config_file) as in_handle: old_config = yaml.safe_load(in_handle) fc_date = old_config["fc_date"] else: fc_date = datetime.datetime.now().strftime("%y%m%d") return fc_date
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/xprize.py#L32-L41
how to get current date
python
def date(self, field=None, val=None): """ Like datetime, but truncated to be a date only """ return self.datetime(field=field, val=val).date()
https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/base.py#L135-L139
how to get current date
python
def get_period_last_30_days() -> str: """ Returns the last week as a period string """ today = Datum() today.today() # start_date = today - timedelta(days=30) start_date = today.clone() start_date.subtract_days(30) period = get_period(start_date.value, today.value) return period
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L83-L92
how to get current date
python
def get_timestamp(self): """Return the latest timestamp from among our children""" stamp = 0 for kid in self.children(): if kid.get_timestamp() > stamp: stamp = kid.get_timestamp() return stamp
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Node/FS.py#L1876-L1882
how to get current date
python
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L228-L233
how to get current date
python
def get_month_start_date(self): """Returns the first day of the current month""" now = timezone.now() return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/management/commands/migrate_active_to_published.py#L10-L13