我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用datetime.date.date()。
def format_week(self, char, num): if char.islower(): # week of year day_of_year = self.get_day_of_year() week = self.get_week_number(day_of_year) if week == 0: date = self.value - timedelta(days=day_of_year) week = self.get_week_number(self.get_day_of_year(date), date.weekday()) return self.format(week, num) else: # week of month week = self.get_week_number(self.value.day) if week == 0: date = self.value - timedelta(days=self.value.day) week = self.get_week_number(date.day, date.weekday()) pass return '%d' % week
def day_class(date): # day type dayofweek = date.dayofweek date = date.date() if date in BeforeNationlDay: return 'BeforeNationalDay' elif date in NationalDayStart: return 'NationalDayStart' elif date in NationalDayEnd: return 'NationalDayEnd' elif date in WorkingWeekend: return 'WorkingWeekend' elif date in WorkingWeekend: return 'WorkingWeek' elif dayofweek in range(5): return 'WorkingDay' else: return 'Weekend'
def __init__(self, activates, from_tzinfo, to_tzinfo, reference_date=None): #: the time of the activation of the timezone transition in UTC. self.activates = activates #: the timezone from where the transition starts. self.from_tzinfo = from_tzinfo #: the timezone for after the transition. self.to_tzinfo = to_tzinfo #: the reference date that was provided. This is the `dt` parameter #: to the :func:`get_next_timezone_transition`. self.reference_date = reference_date
def get_date_format(format='medium', locale=LC_TIME): """Return the date formatting patterns used by the locale for the specified format. >>> get_date_format(locale='en_US') <DateTimePattern u'MMM d, y'> >>> get_date_format('full', locale='de_DE') <DateTimePattern u'EEEE, d. MMMM y'> :param format: the format to use, one of "full", "long", "medium", or "short" :param locale: the `Locale` object, or a locale string """ return Locale.parse(locale).date_formats[format]
def format_date(date=None, format='medium', locale=LC_TIME): """Return a date formatted according to the given pattern. >>> d = date(2007, 04, 01) >>> format_date(d, locale='en_US') u'Apr 1, 2007' >>> format_date(d, format='full', locale='de_DE') u'Sonntag, 1. April 2007' If you don't want to use the locale default formats, you can specify a custom date pattern: >>> format_date(d, "EEE, MMM d, ''yy", locale='en') u"Sun, Apr 1, '07" :param date: the ``date`` or ``datetime`` object; if `None`, the current date is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param locale: a `Locale` object or a locale identifier """ if date is None: date = date_.today() elif isinstance(date, datetime): date = date.date() locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): format = get_date_format(format, locale=locale) pattern = parse_pattern(format) return pattern.apply(date, locale)
def parse_date(string, locale=LC_TIME): """Parse a date from a string. This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string. >>> parse_date('4/1/04', locale='en_US') datetime.date(2004, 4, 1) >>> parse_date('01.04.2004', locale='de_DE') datetime.date(2004, 4, 1) :param string: the string containing the date :param locale: a `Locale` object or a locale identifier """ # TODO: try ISO format first? format = get_date_format(locale=locale).pattern.lower() year_idx = format.index('y') month_idx = format.index('m') if month_idx < 0: month_idx = format.index('l') day_idx = format.index('d') indexes = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] indexes.sort() indexes = dict([(item[1], idx) for idx, item in enumerate(indexes)]) # FIXME: this currently only supports numbers, but should also support month # names, both in the requested locale, and english numbers = re.findall('(\d+)', string) year = numbers[indexes['Y']] if len(year) == 2: year = 2000 + int(year) else: year = int(year) month = int(numbers[indexes['M']]) day = int(numbers[indexes['D']]) if month > 12: month, day = day, month return date(year, month, day)
def __init__(self, value, locale): assert isinstance(value, (date, datetime, time)) if isinstance(value, (datetime, time)) and value.tzinfo is None: value = value.replace(tzinfo=UTC) self.value = value self.locale = Locale.parse(locale)
def get_day_of_year(self, date=None): if date is None: date = self.value return (date - date.replace(month=1, day=1)).days + 1
def format_date(date=None, format='medium', locale=LC_TIME): """Return a date formatted according to the given pattern. >>> d = date(2007, 4, 1) >>> format_date(d, locale='en_US') u'Apr 1, 2007' >>> format_date(d, format='full', locale='de_DE') u'Sonntag, 1. April 2007' If you don't want to use the locale default formats, you can specify a custom date pattern: >>> format_date(d, "EEE, MMM d, ''yy", locale='en') u"Sun, Apr 1, '07" :param date: the ``date`` or ``datetime`` object; if `None`, the current date is used :param format: one of "full", "long", "medium", or "short", or a custom date/time pattern :param locale: a `Locale` object or a locale identifier """ if date is None: date = date_.today() elif isinstance(date, datetime): date = date.date() locale = Locale.parse(locale) if format in ('full', 'long', 'medium', 'short'): format = get_date_format(format, locale=locale) pattern = parse_pattern(format) return pattern.apply(date, locale)
def format_week(self, char, num): if char.islower(): # week of year day_of_year = self.get_day_of_year() week = self.get_week_number(day_of_year) if week == 0: date = self.value - timedelta(days=day_of_year) week = self.get_week_number(self.get_day_of_year(date), date.weekday()) return self.format(week, num) else: # week of month week = self.get_week_number(self.value.day) if week == 0: date = self.value - timedelta(days=self.value.day) week = self.get_week_number(date.day, date.weekday()) return '%d' % week
def sarimax_preparation_main(volume, test_volume, weather_train_file, weather_train_new_file, weather_test_file): train_data = volume.pivot(columns='id', values='volume') test_data = test_volume.pivot(columns='id', values='volume') tmp = pd.DataFrame({'T1D0':np.NaN,'T1D1':np.NaN,'T2D0':np.NaN,'T3D0':np.NaN,'T3D1':np.NaN},index=pd.date_range(start=datetime(2016,10,18)+Day(7),end=datetime(2016,10,25)+Day(7),freq='20min',closed='left')) tmp.set_value(test_data.index,test_data.columns, test_data.values) train_data = pd.concat((train_data, tmp)) peakDummies = pd.get_dummies(train_data.index.map(peak_time)) peakDummies.index = train_data.index dayDummies = pd.get_dummies(train_data.index.map(day_class)) dayDummies.index = train_data.index train_data = pd.concat([train_data,peakDummies, dayDummies],axis=1) weather_train = pd.read_csv(weather_train_file) weather_train_new = pd.read_csv(weather_train_new_file) weather_test = pd.read_csv(weather_test_file) weather_full = pd.concat([weather_train, weather_train_new, weather_test]).reset_index() weather_full.precipitation = weather_full.precipitation * 4 weather_full['precipitation'] = weather_full.precipitation.map( precipitation_grade) rain_dummies = pd.get_dummies(weather_full.precipitation) weather_feature = weather_full[['date', 'hour']].join(rain_dummies) weather_feature.index = weather_feature.apply(get_py_datetime, axis=1) weather_feature = weather_feature.resample('20min').first() weather_feature = weather_feature.fillna(method='ffill') weather_feature['diff'] = np.abs(weather_feature.index.map( lambda dt: dt.hour) - weather_feature.hour) weather_feature[weather_feature['diff'] >= 3] = np.nan del weather_feature['diff'],weather_feature['date'],weather_feature['hour'] train_data = train_data.join(weather_feature) train_data.to_csv('sarimax_data.csv',index=True)
def get_next_timezone_transition(zone=None, dt=None): """Given a timezone it will return a :class:`TimezoneTransition` object that holds the information about the next timezone transition that's going to happen. For instance this can be used to detect when the next DST change is going to happen and how it looks like. The transition is calculated relative to the given datetime object. The next transition that follows the date is used. If a transition cannot be found the return value will be `None`. Transition information can only be provided for timezones returned by the :func:`get_timezone` function. :param zone: the timezone for which the transition should be looked up. If not provided the local timezone is used. :param dt: the date after which the next transition should be found. If not given the current time is assumed. """ zone = get_timezone(zone) if dt is None: dt = datetime.utcnow() else: dt = dt.replace(tzinfo=None) if not hasattr(zone, '_utc_transition_times'): raise TypeError('Given timezone does not have UTC transition ' 'times. This can happen because the operating ' 'system fallback local timezone is used or a ' 'custom timezone object') try: idx = max(0, bisect_right(zone._utc_transition_times, dt)) old_trans = zone._transition_info[idx - 1] new_trans = zone._transition_info[idx] old_tz = zone._tzinfos[old_trans] new_tz = zone._tzinfos[new_trans] except (LookupError, ValueError): return None return TimezoneTransition( activates=zone._utc_transition_times[idx], from_tzinfo=old_tz, to_tzinfo=new_tz, reference_date=dt )
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): """Return the timezone associated with the given `datetime` object formatted as string indicating the offset from GMT. >>> dt = datetime(2007, 4, 1, 15, 30) >>> get_timezone_gmt(dt, locale='en') u'GMT+00:00' >>> tz = get_timezone('America/Los_Angeles') >>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz) >>> get_timezone_gmt(dt, locale='en') u'GMT-08:00' >>> get_timezone_gmt(dt, 'short', locale='en') u'-0800' The long format depends on the locale, for example in France the acronym UTC string is used instead of GMT: >>> get_timezone_gmt(dt, 'long', locale='fr_FR') u'UTC-08:00' .. versionadded:: 0.9 :param datetime: the ``datetime`` object; if `None`, the current date and time in UTC is used :param width: either "long" or "short" :param locale: the `Locale` object, or a locale string """ if datetime is None: datetime = datetime_.utcnow() elif isinstance(datetime, integer_types): datetime = datetime_.utcfromtimestamp(datetime).time() if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) locale = Locale.parse(locale) offset = datetime.tzinfo.utcoffset(datetime) seconds = offset.days * 24 * 60 * 60 + offset.seconds hours, seconds = divmod(seconds, 3600) if width == 'short': pattern = u'%+03d%02d' else: pattern = locale.zone_formats['gmt'] % '%+03d:%02d' return pattern % (hours, seconds // 60)
def __getitem__(self, name): char = name[0] num = len(name) if char == 'G': return self.format_era(char, num) elif char in ('y', 'Y', 'u'): return self.format_year(char, num) elif char in ('Q', 'q'): return self.format_quarter(char, num) elif char in ('M', 'L'): return self.format_month(char, num) elif char in ('w', 'W'): return self.format_week(char, num) elif char == 'd': return self.format(self.value.day, num) elif char == 'D': return self.format_day_of_year(num) elif char == 'F': return self.format_day_of_week_in_month() elif char in ('E', 'e', 'c'): return self.format_weekday(char, num) elif char == 'a': return self.format_period(char) elif char == 'h': if self.value.hour % 12 == 0: return self.format(12, num) else: return self.format(self.value.hour % 12, num) elif char == 'H': return self.format(self.value.hour, num) elif char == 'K': return self.format(self.value.hour % 12, num) elif char == 'k': if self.value.hour == 0: return self.format(24, num) else: return self.format(self.value.hour, num) elif char == 'm': return self.format(self.value.minute, num) elif char == 's': return self.format(self.value.second, num) elif char == 'S': return self.format_frac_seconds(num) elif char == 'A': return self.format_milliseconds_in_day(num) elif char in ('z', 'Z', 'v', 'V'): return self.format_timezone(char, num) else: raise KeyError('Unsupported date/time field %r' % char)
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME): """Return the timezone associated with the given `datetime` object formatted as string indicating the offset from GMT. >>> dt = datetime(2007, 4, 1, 15, 30) >>> get_timezone_gmt(dt, locale='en') u'GMT+00:00' >>> tz = get_timezone('America/Los_Angeles') >>> dt = tz.localize(datetime(2007, 4, 1, 15, 30)) >>> get_timezone_gmt(dt, locale='en') u'GMT-07:00' >>> get_timezone_gmt(dt, 'short', locale='en') u'-0700' The long format depends on the locale, for example in France the acronym UTC string is used instead of GMT: >>> get_timezone_gmt(dt, 'long', locale='fr_FR') u'UTC-07:00' .. versionadded:: 0.9 :param datetime: the ``datetime`` object; if `None`, the current date and time in UTC is used :param width: either "long" or "short" :param locale: the `Locale` object, or a locale string """ if datetime is None: datetime = datetime_.utcnow() elif isinstance(datetime, integer_types): datetime = datetime_.utcfromtimestamp(datetime).time() if datetime.tzinfo is None: datetime = datetime.replace(tzinfo=UTC) locale = Locale.parse(locale) offset = datetime.tzinfo.utcoffset(datetime) seconds = offset.days * 24 * 60 * 60 + offset.seconds hours, seconds = divmod(seconds, 3600) if width == 'short': pattern = u'%+03d%02d' else: pattern = locale.zone_formats['gmt'] % '%+03d:%02d' return pattern % (hours, seconds // 60)