query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
string to date
|
python
|
def date_to_string(date):
"""Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34))
'2012-01-03T12:23:34'
>>> date_to_string(datetime.date(2012, 1, 3))
'2012-01-03'
"""
if isinstance(date, datetime.datetime):
# Create an ISO 8601 datetime string
date_str = date.strftime('%Y-%m-%dT%H:%M:%S')
tzstr = date.strftime('%z')
if tzstr:
# Yes, this is ugly. And no, I haven't found a better way to have a
# truly ISO 8601 datetime with timezone in Python.
date_str = '%s%s:%s' % (date_str, tzstr[0:3], tzstr[3:5])
elif isinstance(date, datetime.date):
# Create an ISO 8601 date string
date_str = date.strftime('%Y-%m-%d')
else:
raise TypeError('Argument is not a date or datetime. ')
return date_str
|
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/datetimeutil.py#L94-L120
|
string to date
|
python
|
def toString(self):
""" Returns date as string. """
slist = self.toList()
sign = '' if slist[0] == '+' else '-'
string = '/'.join(['%02d' % v for v in slist[1:]])
return sign + string
|
https://github.com/flatangle/flatlib/blob/44e05b2991a296c678adbc17a1d51b6a21bc867c/flatlib/datetime.py#L93-L98
|
string to 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
|
string to 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
|
string to date
|
python
|
def date_string_to_date(p_date):
"""
Given a date in YYYY-MM-DD, returns a Python date object. Throws a
ValueError if the date is invalid.
"""
result = None
if p_date:
parsed_date = re.match(r'(\d{4})-(\d{2})-(\d{2})', p_date)
if parsed_date:
result = date(
int(parsed_date.group(1)), # year
int(parsed_date.group(2)), # month
int(parsed_date.group(3)) # day
)
else:
raise ValueError
return result
|
https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/lib/Utils.py#L28-L46
|
string to date
|
python
|
def stringToDateTime(s, tzinfo=None):
"""
Returns datetime.datetime object.
"""
try:
year = int(s[0:4])
month = int(s[4:6])
day = int(s[6:8])
hour = int(s[9:11])
minute = int(s[11:13])
second = int(s[13:15])
if len(s) > 15:
if s[15] == 'Z':
tzinfo = getTzid('UTC')
except:
raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
year = year and year or 2000
if tzinfo is not None and hasattr(tzinfo,'localize'): # PyTZ case
return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
|
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/icalendar.py#L1726-L1745
|
string to date
|
python
|
def stringToDateTime(s, tzinfo=None):
"""Returns datetime.datetime object."""
try:
year = int(s[0:4])
month = int(s[4:6])
day = int(s[6:8])
hour = int(s[9:11])
minute = int(s[11:13])
second = int(s[13:15])
if len(s) > 15:
if s[15] == 'Z':
tzinfo = utc
except:
raise ParseError("'%s' is not a valid DATE-TIME" % s)
year = year and year or 2000
return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
|
https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L1620-L1635
|
string to date
|
python
|
def string_to_date(input):
"""Convert string to date object.
:param input: the date string to parse
:type input: str
:returns: the parsed datetime object
:rtype: datetime.datetime
"""
# try date formats --mmdd, --mm-dd, yyyymmdd, yyyy-mm-dd and datetime
# formats yyyymmddThhmmss, yyyy-mm-ddThh:mm:ss, yyyymmddThhmmssZ,
# yyyy-mm-ddThh:mm:ssZ.
for format_string in ("--%m%d", "--%m-%d", "%Y%m%d", "%Y-%m-%d",
"%Y%m%dT%H%M%S", "%Y-%m-%dT%H:%M:%S",
"%Y%m%dT%H%M%SZ", "%Y-%m-%dT%H:%M:%SZ"):
try:
return datetime.strptime(input, format_string)
except ValueError:
pass
# try datetime formats yyyymmddThhmmsstz and yyyy-mm-ddThh:mm:sstz where tz
# may look like -06:00.
for format_string in ("%Y%m%dT%H%M%S%z", "%Y-%m-%dT%H:%M:%S%z"):
try:
return datetime.strptime(''.join(input.rsplit(":", 1)),
format_string)
except ValueError:
pass
raise ValueError
|
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/helpers.py#L81-L107
|
string to date
|
python
|
def date(value):
"""
Returns a date literal if value is likely coercible to a date
Parameters
----------
value : date value as string
Returns
--------
result : TimeScalar
"""
if isinstance(value, str):
value = to_date(value)
return literal(value, type=dt.date)
|
https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L277-L291
|
string to date
|
python
|
def to_string(self, style=None, utcoffset=None):
"""Return a |str| object representing the actual date in
accordance with the given style and the eventually given
UTC offset (in minutes).
Without any input arguments, the actual |Date.style| is used
to return a date string in your local time zone:
>>> from hydpy import Date
>>> date = Date('01.11.1997 00:00:00')
>>> date.to_string()
'01.11.1997 00:00:00'
Passing a style string affects the returned |str| object, but
not the |Date.style| property:
>>> date.style
'din1'
>>> date.to_string(style='iso2')
'1997-11-01 00:00:00'
>>> date.style
'din1'
When passing the `utcoffset` in minutes, the offset string is
appended:
>>> date.to_string(style='iso2', utcoffset=60)
'1997-11-01 00:00:00+01:00'
If the given offset does not correspond to your local offset
defined by |Options.utcoffset| (which defaults to UTC+01:00),
the date string is adapted:
>>> date.to_string(style='iso1', utcoffset=0)
'1997-10-31T23:00:00+00:00'
"""
if not style:
style = self.style
if utcoffset is None:
string = ''
date = self.datetime
else:
sign = '+' if utcoffset >= 0 else '-'
hours = abs(utcoffset // 60)
minutes = abs(utcoffset % 60)
string = f'{sign}{hours:02d}:{minutes:02d}'
offset = utcoffset-hydpy.pub.options.utcoffset
date = self.datetime + datetime.timedelta(minutes=offset)
return date.strftime(self._formatstrings[style]) + string
|
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L686-L734
|
string to 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
|
string to date
|
python
|
def parseDateText(self, dateString):
"""
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
"""
yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
currentMth = mth
currentDy = dy
s = dateString.lower()
m = self.ptc.CRE_DATE3.search(s)
mth = m.group('mthname')
mth = self.ptc.MonthOffsets[mth]
if m.group('day') != None:
dy = int(m.group('day'))
else:
dy = 1
if m.group('year') != None:
yr = int(m.group('year'))
# birthday epoch constraint
if yr < self.ptc.BirthdayEpoch:
yr += 2000
elif yr < 100:
yr += 1900
elif (mth < currentMth) or (mth == currentMth and dy < currentDy):
# if that day and month have already passed in this year,
# then increment the year by 1
yr += 1
if dy > 0 and dy <= self.ptc.daysInMonth(mth, yr):
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
else:
# Return current time if date string is invalid
self.dateFlag = 0
self.timeFlag = 0
sourceTime = time.localtime()
return sourceTime
|
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L389-L440
|
string to date
|
python
|
def parseDate(self, dateString):
"""
Parse short-form date strings::
'05/28/2006' or '04.21'
@type dateString: string
@param dateString: text to convert to a C{datetime}
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
"""
yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
# values pulled from regex's will be stored here and later
# assigned to mth, dy, yr based on information from the locale
# -1 is used as the marker value because we want zero values
# to be passed thru so they can be flagged as errors later
v1 = -1
v2 = -1
v3 = -1
s = dateString
m = self.ptc.CRE_DATE2.search(s)
if m is not None:
index = m.start()
v1 = int(s[:index])
s = s[index + 1:]
m = self.ptc.CRE_DATE2.search(s)
if m is not None:
index = m.start()
v2 = int(s[:index])
v3 = int(s[index + 1:])
else:
v2 = int(s.strip())
v = [ v1, v2, v3 ]
d = { 'm': mth, 'd': dy, 'y': yr }
for i in range(0, 3):
n = v[i]
c = self.ptc.dp_order[i]
if n >= 0:
d[c] = n
# if the year is not specified and the date has already
# passed, increment the year
if v3 == -1 and ((mth > d['m']) or (mth == d['m'] and dy > d['d'])):
yr = d['y'] + 1
else:
yr = d['y']
mth = d['m']
dy = d['d']
# birthday epoch constraint
if yr < self.ptc.BirthdayEpoch:
yr += 2000
elif yr < 100:
yr += 1900
if _debug:
print 'parseDate: ', yr, mth, dy, self.ptc.daysInMonth(mth, yr)
if (mth > 0 and mth <= 12) and \
(dy > 0 and dy <= self.ptc.daysInMonth(mth, yr)):
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
else:
self.dateFlag = 0
self.timeFlag = 0
sourceTime = time.localtime() # return current time if date
# string is invalid
return sourceTime
|
https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/parsedatetime/parsedatetime.py#L312-L386
|
string to date
|
python
|
def datetime_string(day, month, year, hour, minute):
"""Build a date string using the provided day, month, year numbers.
Automatically adds a leading zero to ``day`` and ``month`` if they only have
one digit.
Args:
day (int): Day number.
month(int): Month number.
year(int): Year number.
hour (int): Hour of the day in 24h format.
minute (int): Minute of the hour.
Returns:
str: Date in the format *YYYY-MM-DDThh:mm:ss*.
"""
# Overflow
if hour < 0 or hour > 23: hour = 0
if minute < 0 or minute > 60: minute = 0
return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute)
|
https://github.com/rmed/pyemtmad/blob/c21c42d0c7b50035dfed29540d7e64ab67833728/pyemtmad/util.py#L87-L107
|
string to date
|
python
|
def _date_by_len(self, string):
"""
Parses a date from a string based on its length
:param string:
A unicode string to parse
:return:
A datetime.datetime object or a unicode string
"""
strlen = len(string)
year_num = int(string[0:2])
if year_num < 50:
prefix = '20'
else:
prefix = '19'
if strlen == 10:
return datetime.strptime(prefix + string, '%Y%m%d%H%M')
if strlen == 12:
return datetime.strptime(prefix + string, '%Y%m%d%H%M%S')
return string
|
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4692-L4717
|
string to date
|
python
|
def to_datetime_string(self) -> str:
""" Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56
"""
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}"
|
https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L196-L202
|
string to date
|
python
|
def string_to_date(value):
"""
Return a Python date that corresponds to the specified string
representation.
@param value: string representation of a date.
@return: an instance ``datetime.datetime`` represented by the string.
"""
if isinstance(value, datetime.date):
return value
return dateutil.parser.parse(value).date()
|
https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/utils/cast.py#L172-L184
|
string to date
|
python
|
def string_to_data_time(d):
'''
simple parse date string, such as:
2016-5-27 21:22:20
2016-05-27 21:22:2
2016/05/27 21:22:2
2016-05-27
2016/5/27
21:22:2
'''
if d:
d = d.replace('/', '-')
if ' ' in d:
_datetime = d.split(' ')
if len(_datetime) == 2:
_d = _string_to_date(_datetime[0])
_t = _string_to_time(_datetime[1])
return _combine_date_time(_d, _t)
else:
# no space
if '-' in d:
return date_to_datetime(_string_to_date(d))
elif ':' in d:
return time_to_datetime(_string_to_time(d))
return None
|
https://github.com/hustcc/timeago/blob/819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613/src/timeago/parser.py#L74-L100
|
string to date
|
python
|
def from_str(date):
"""
Given a date in the format: Jan,21st.2015
will return a datetime of it.
"""
month = date[:3][0] + date[:3][-2:].lower()
if month not in NAMED_MONTHS:
raise CanNotFormatError('Month not recognized')
date = date.replace(',', '').replace(' ', '').replace('.', '')
try:
day_unit = [x for x in ['st', 'rd', 'nd', 'th'] if x in date][0]
day = int(re.search(r'\d+', date.split(day_unit)[0]).group())
year = int(re.search(r'\d+', date.split(day_unit)[1]).group())
numeric_month = NAMED_MONTHS[month]
return datetime.date(int(year), numeric_month, day)
except:
raise CanNotFormatError('Not well formatted. Expecting something like May,21st.2015')
|
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L259-L276
|
string to date
|
python
|
def convert_date(d, custom_date_string=None, fallback=None):
"""
for whatever reason, sometimes WP XML has unintelligible
datetime strings for pubDate.
In this case default to custom_date_string or today
Use fallback in case a secondary date string is available.
Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000'
shows up.
>>> xp = XML_parser
>>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000")
'2015-03-30'
"""
if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback:
d = fallback
try:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z'))
except ValueError:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S'))
except ValueError:
date = custom_date_string or datetime.datetime.today().strftime("%Y-%m-%d")
return date
|
https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L132-L153
|
string to date
|
python
|
def parseDateText(self, dateString, sourceTime=None):
"""
Parse long-form date strings::
'May 31st, 2006'
'Jan 1st'
'July 2006'
@type dateString: string
@param dateString: text to convert to a datetime
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
"""
if sourceTime is None:
yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
else:
yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime
currentMth = mth
currentDy = dy
accuracy = []
debug and log.debug('parseDateText currentMth %s currentDy %s',
mth, dy)
s = dateString.lower()
m = self.ptc.CRE_DATE3.search(s)
mth = m.group('mthname')
mth = self.ptc.MonthOffsets[mth]
accuracy.append('month')
if m.group('day') is not None:
dy = int(m.group('day'))
accuracy.append('day')
else:
dy = 1
if m.group('year') is not None:
yr = int(m.group('year'))
accuracy.append('year')
# birthday epoch constraint
if yr < self.ptc.BirthdayEpoch:
yr += 2000
elif yr < 100:
yr += 1900
elif (mth < currentMth) or (mth == currentMth and dy < currentDy):
# if that day and month have already passed in this year,
# then increment the year by 1
yr += self.ptc.YearParseStyle
with self.context() as ctx:
if dy > 0 and dy <= self.ptc.daysInMonth(mth, yr):
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
ctx.updateAccuracy(*accuracy)
else:
# Return current time if date string is invalid
sourceTime = time.localtime()
debug and log.debug('parseDateText returned '
'mth %d dy %d yr %d sourceTime %s',
mth, dy, yr, sourceTime)
return sourceTime
|
https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L483-L550
|
string to date
|
python
|
def _parse_date_string(date_str):
"""
Get a datetime.date object from a string date representation.
The FCS standard includes an optional keyword parameter $DATE in
which the acquistion date is stored. In FCS 2.0, the date is saved
as 'dd-mmm-yy', whereas in FCS 3.0 and 3.1 the date is saved as
'dd-mmm-yyyy'.
This function attempts to parse these formats, along with a couple
of nonstandard ones, using the datetime module.
Parameters:
-----------
date_str : str, or None
String representation of date, or None.
Returns:
--------
t : datetime.datetime, or None
Date parsed from `date_str`. If parsing was not possible,
return None. If `date_str` is None, return None
"""
# If input is None, return None
if date_str is None:
return None
# Standard format for FCS2.0
try:
return datetime.datetime.strptime(date_str, '%d-%b-%y')
except ValueError:
pass
# Standard format for FCS3.0
try:
return datetime.datetime.strptime(date_str, '%d-%b-%Y')
except ValueError:
pass
# Nonstandard format 1
try:
return datetime.datetime.strptime(date_str, '%y-%b-%d')
except ValueError:
pass
# Nonstandard format 2
try:
return datetime.datetime.strptime(date_str, '%Y-%b-%d')
except ValueError:
pass
# If none of these formats work, return None
return None
|
https://github.com/taborlab/FlowCal/blob/031a7af82acb1d46879a8e384a1a00f27f0bdc7a/FlowCal/io.py#L1827-L1877
|
string to date
|
python
|
def parse_date(string_date):
"""
Parse the given date as one of the following
* Git internal format: timestamp offset
* RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
* ISO 8601 2005-04-07T22:13:13
The T can be a space as well
:return: Tuple(int(timestamp_UTC), int(offset)), both in seconds since epoch
:raise ValueError: If the format could not be understood
:note: Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY.
"""
# git time
try:
if string_date.count(' ') == 1 and string_date.rfind(':') == -1:
timestamp, offset = string_date.split()
timestamp = int(timestamp)
return timestamp, utctz_to_altz(verify_utctz(offset))
else:
offset = "+0000" # local time by default
if string_date[-5] in '-+':
offset = verify_utctz(string_date[-5:])
string_date = string_date[:-6] # skip space as well
# END split timezone info
offset = utctz_to_altz(offset)
# now figure out the date and time portion - split time
date_formats = []
splitter = -1
if ',' in string_date:
date_formats.append("%a, %d %b %Y")
splitter = string_date.rfind(' ')
else:
# iso plus additional
date_formats.append("%Y-%m-%d")
date_formats.append("%Y.%m.%d")
date_formats.append("%m/%d/%Y")
date_formats.append("%d.%m.%Y")
splitter = string_date.rfind('T')
if splitter == -1:
splitter = string_date.rfind(' ')
# END handle 'T' and ' '
# END handle rfc or iso
assert splitter > -1
# split date and time
time_part = string_date[splitter + 1:] # skip space
date_part = string_date[:splitter]
# parse time
tstruct = time.strptime(time_part, "%H:%M:%S")
for fmt in date_formats:
try:
dtstruct = time.strptime(date_part, fmt)
utctime = calendar.timegm((dtstruct.tm_year, dtstruct.tm_mon, dtstruct.tm_mday,
tstruct.tm_hour, tstruct.tm_min, tstruct.tm_sec,
dtstruct.tm_wday, dtstruct.tm_yday, tstruct.tm_isdst))
return int(utctime), offset
except ValueError:
continue
# END exception handling
# END for each fmt
# still here ? fail
raise ValueError("no format matched")
# END handle format
except Exception:
raise ValueError("Unsupported date format: %s" % string_date)
|
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/util.py#L131-L202
|
string to date
|
python
|
def str_to_datetime(ts):
"""Format a string to a datetime object.
This functions supports several date formats like YYYY-MM-DD, MM-DD-YYYY
and YY-MM-DD. When the given data is None or an empty string, the function
returns None.
:param ts: string to convert
:returns: a datetime object
:raises IvalidDateError: when the given string cannot be converted into
a valid date
"""
if not ts:
return None
try:
return dateutil.parser.parse(ts).replace(tzinfo=None)
except Exception:
raise InvalidDateError(date=str(ts))
|
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L87-L107
|
string to date
|
python
|
def stringToDate(fmt="%Y-%m-%d"):
"""returns a function to convert a string to a datetime.date instance
using the formatting string fmt as in time.strftime"""
import time
import datetime
def conv_func(s):
return datetime.date(*time.strptime(s,fmt)[:3])
return conv_func
|
https://github.com/andreasjansson/head-in-the-clouds/blob/32c1d00d01036834dc94368e7f38b0afd3f7a82f/headintheclouds/dependencies/PyDbLite/PyDbLiteConv.py#L3-L10
|
string to 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
|
string to date
|
python
|
def parse_date(date_string):
"""
Parse the given string as datetime object. This parser supports in almost any string formats.
For relative times, like `10min ago`, this parser computes the actual time relative to current UTC time. This
allows time to always be in UTC if an explicit time zone is not provided.
Parameters
----------
date_string : str
String representing the date
Returns
-------
datetime.datetime
Parsed datetime object. None, if the string cannot be parsed.
"""
parser_settings = {
# Relative times like '10m ago' must subtract from the current UTC time. Without this setting, dateparser
# will use current local time as the base for subtraction, but falsely assume it is a UTC time. Therefore
# the time that dateparser returns will be a `datetime` object that did not have any timezone information.
# So be explicit to set the time to UTC.
"RELATIVE_BASE": datetime.datetime.utcnow()
}
return dateparser.parse(date_string, settings=parser_settings)
|
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/time.py#L91-L117
|
string to date
|
python
|
def to_dates(param):
"""
This function takes a date string in various formats
and converts it to a normalized and validated date range. A list
with two elements is returned, lower and upper date boundary.
Valid inputs are, for example:
2012 => Jan 1 20012 - Dec 31 2012 (whole year)
201201 => Jan 1 2012 - Jan 31 2012 (whole month)
2012101 => Jan 1 2012 - Jan 1 2012 (whole day)
2011-2011 => same as "2011", which means whole year 2012
2011-2012 => Jan 1 2011 - Dec 31 2012 (two years)
201104-2012 => Apr 1 2011 - Dec 31 2012
201104-201203 => Apr 1 2011 - March 31 2012
20110408-2011 => Apr 8 2011 - Dec 31 2011
20110408-201105 => Apr 8 2011 - May 31 2011
20110408-20110507 => Apr 8 2011 - May 07 2011
2011- => Jan 1 2012 - Dec 31 9999 (unlimited)
201104- => Apr 1 2011 - Dec 31 9999 (unlimited)
20110408- => Apr 8 2011 - Dec 31 9999 (unlimited)
-2011 Jan 1 0000 - Dez 31 2011
-201104 Jan 1 0000 - Apr 30, 2011
-20110408 Jan 1 0000 - Apr 8, 2011
"""
pos = param.find('-')
lower, upper = (None, None)
if pos == -1:
# no seperator given
lower, upper = (param, param)
else:
lower, upper = param.split('-')
ret = (expand_date_param(lower, 'lower'), expand_date_param(upper, 'upper'))
return ret
|
https://github.com/marians/py-daterangestr/blob/fa5dd78c8fea5f91a85bf732af8a0bc307641134/daterangestr.py#L33-L65
|
string to date
|
python
|
def parse_date(self, value):
"""
A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if isinstance(value, sixmini.string_types):
return self.str2date(value)
elif value is None:
raise TypeError("Unable to parse date from %r" % value)
elif isinstance(value, sixmini.integer_types):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise ValueError("Unable to parse date from %r" % value)
|
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L226-L248
|
string to date
|
python
|
def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t)
|
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L171-L175
|
string to date
|
python
|
def dateparser(fmt, strict=True):
"""Return a function to parse strings as :class:`datetime.date` objects
using a given format. E.g.::
>>> from petl import dateparser
>>> isodate = dateparser('%Y-%m-%d')
>>> isodate('2002-12-25')
datetime.date(2002, 12, 25)
>>> try:
... isodate('2002-02-30')
... except ValueError as e:
... print(e)
...
day is out of range for month
If ``strict=False`` then if an error occurs when parsing, the original
value will be returned as-is, and no error will be raised.
"""
def parser(value):
try:
return datetime.datetime.strptime(value.strip(), fmt).date()
except Exception as e:
if strict:
raise e
else:
return value
return parser
|
https://github.com/petl-developers/petl/blob/1d33ca055f7e04e0d28a772041c9fd30c8d415d6/petl/util/parsers.py#L39-L67
|
string to date
|
python
|
def str2date(self, datestr):
"""Try parse date from string. If None template matching this datestr,
raise Error.
:param datestr: a string represent a date
:type datestr: str
:return: a datetime.date object
Usage::
>>> from weatherlab.lib.timelib.timewrapper import timewrapper
>>> timewrapper.str2date("12/15/2014")
datetime.date(2014, 12, 15)
**中文文档**
尝试从字符串中解析出datetime.date对象。每次解析时, 先尝试默认模板, 如果
失败了, 再重新对所有模板进行尝试; 一旦尝试成功, 这将当前成功的模板保存
为默认模板。这样使得尝试的策略最优化。
"""
try:
return datetime.strptime(
datestr, self.default_date_template).date()
except: # 如果默认的模板不匹配, 则重新尝试所有的模板
pass
# try all date_templates
# 对每个template进行尝试, 如果都不成功, 抛出异常
for template in self.date_templates:
try:
a_datetime = datetime.strptime(datestr, template) # 如果成功了
self.default_date_template = template # 保存为default
return a_datetime.date()
except:
pass
raise NoMatchingTemplateError(datestr)
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/timelib/timewrapper.py#L190-L225
|
string to date
|
python
|
def parse_date(string, formation=None):
"""
string to date stamp
:param string: date string
:param formation: format string
:return: datetime.date
"""
if formation:
_stamp = datetime.datetime.strptime(string, formation).date()
return _stamp
_string = string.replace('.', '-').replace('/', '-')
if '-' in _string:
if len(_string.split('-')[0]) > 3 or len(_string.split('-')[2]) > 3:
try:
_stamp = datetime.datetime.strptime(_string, '%Y-%m-%d').date()
except ValueError:
try:
_stamp = datetime.datetime.strptime(_string, '%m-%d-%Y').date()
except ValueError:
_stamp = datetime.datetime.strptime(_string, '%d-%m-%Y').date()
else:
try:
_stamp = datetime.datetime.strptime(_string, '%y-%m-%d').date()
except ValueError:
try:
_stamp = datetime.datetime.strptime(_string, '%m-%d-%y').date()
except ValueError:
_stamp = datetime.datetime.strptime(_string, '%d-%m-%y').date()
else:
if len(_string) > 6:
try:
_stamp = datetime.datetime.strptime(_string, '%Y%m%d').date()
except ValueError:
_stamp = datetime.datetime.strptime(_string, '%m%d%Y').date()
elif len(_string) <= 6:
try:
_stamp = datetime.datetime.strptime(_string, '%y%m%d').date()
except ValueError:
_stamp = datetime.datetime.strptime(_string, '%m%d%y').date()
else:
raise CanNotFormatError
return _stamp
|
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L178-L220
|
string to date
|
python
|
def _datetime_to_date(arg):
"""
convert datetime/str to date
:param arg:
:return:
"""
_arg = parse(arg)
if isinstance(_arg, datetime.datetime):
_arg = _arg.date()
return _arg
|
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/pytime.py#L182-L191
|
string to date
|
python
|
def to_date(dt, tzinfo=None, format=None):
"""
Convert a datetime to date with tzinfo
"""
d = to_datetime(dt, tzinfo, format)
if not d:
return d
return date(d.year, d.month, d.day)
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L161-L168
|
string to date
|
python
|
def convert_time_string(date_str):
""" Change a date string from the format 2018-08-15T23:55:17 into a datetime object """
dt, _, _ = date_str.partition(".")
dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
return dt
|
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/fileio.py#L29-L33
|
string to date
|
python
|
def str2date(self, date_str):
"""
Parse date from string.
If there's no template matches your string, Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates ASAP.
This method is faster than :meth:`dateutil.parser.parse`.
:param date_str: a string represent a date
:type date_str: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
# try default date template
try:
a_datetime = datetime.strptime(
date_str, self._default_date_template)
return a_datetime.date()
except:
pass
# try every date templates
for template in date_template_list:
try:
a_datetime = datetime.strptime(date_str, template)
self._default_date_template = template
return a_datetime.date()
except:
pass
# raise error
raise ValueError("Unable to parse date from: %r!" % date_str)
|
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/parse.py#L129-L168
|
string to date
|
python
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
https://github.com/developmentseed/landsat-util/blob/92dc81771ddaa64a8a9124a89a6516b52485374b/landsat/utils.py#L213-L232
|
string to date
|
python
|
def parse_date(date_str):
"""
Check if date_str is in a recognised format and return an ISO
yyyy-mm-dd format version if so. Raise DateFormatError if not.
Recognised formats are:
* RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT)
* RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)
* C time (e.g. Wed Dec 4 00:00:00 2002)
* Amz-Date format (e.g. 20090325T010101Z)
* ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00)
date_str -- Str containing a date and optional time
"""
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
'sep', 'oct', 'nov', 'dec']
formats = {
# RFC 7231, e.g. 'Mon, 09 Sep 2011 23:36:00 GMT'
r'^(?:\w{3}, )?(\d{2}) (\w{3}) (\d{4})\D.*$':
lambda m: '{}-{:02d}-{}'.format(
m.group(3),
months.index(m.group(2).lower())+1,
m.group(1)),
# RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)
# assumes current century
r'^\w+day, (\d{2})-(\w{3})-(\d{2})\D.*$':
lambda m: '{}{}-{:02d}-{}'.format(
str(datetime.date.today().year)[:2],
m.group(3),
months.index(m.group(2).lower())+1,
m.group(1)),
# C time, e.g. 'Wed Dec 4 00:00:00 2002'
r'^\w{3} (\w{3}) (\d{1,2}) \d{2}:\d{2}:\d{2} (\d{4})$':
lambda m: '{}-{:02d}-{:02d}'.format(
m.group(3),
months.index(m.group(1).lower())+1,
int(m.group(2))),
# x-amz-date format dates, e.g. 20100325T010101Z
r'^(\d{4})(\d{2})(\d{2})T\d{6}Z$':
lambda m: '{}-{}-{}'.format(*m.groups()),
# ISO 8601 / RFC 3339, e.g. '2009-03-25T10:11:12.13-01:00'
r'^(\d{4}-\d{2}-\d{2})(?:[Tt].*)?$':
lambda m: m.group(1),
}
out_date = None
for regex, xform in formats.items():
m = re.search(regex, date_str)
if m:
out_date = xform(m)
break
if out_date is None:
raise DateFormatError
else:
return out_date
|
https://github.com/sam-washington/requests-aws4auth/blob/1201e470c6d5847b7fe42e937a55755e1895e72c/requests_aws4auth/aws4auth.py#L397-L452
|
string to date
|
python
|
def _convert_date_time_string(dt_string):
'''
convert string to date time object
'''
dt_string = dt_string.split('.')[0]
dt_obj = datetime.strptime(dt_string, '%Y%m%d%H%M%S')
return dt_obj.strftime('%Y-%m-%d %H:%M:%S')
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_system.py#L70-L76
|
string to date
|
python
|
def format_date(cls, timestamp):
"""
Creates a string representing the date information provided by the
given `timestamp` object.
"""
if not timestamp:
raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))
return timestamp.strftime(cls.DATE_FORMAT)
|
https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/date_formatter.py#L30-L38
|
string to 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
|
string to 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
|
string to date
|
python
|
def convert_date(date):
"""Convert string to datetime object."""
date = convert_month(date, shorten=False)
clean_string = convert_string(date)
return datetime.strptime(clean_string, DATE_FMT.replace('-',''))
|
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/utils.py#L91-L95
|
string to date
|
python
|
def str_to_date(self):
"""
Returns the date attribute as a date object.
:returns: Date of the status if it exists.
:rtype: date or NoneType
"""
if hasattr(self, 'date'):
return date(*list(map(int, self.date.split('-'))))
else:
return None
|
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/status.py#L69-L80
|
string to date
|
python
|
def to_iso_datetime(dt):
'''
Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900.
'''
if dt:
date_str = to_iso_date(dt)
time_str = '{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'.format(
dt=dt) if isinstance(dt, datetime) else '00:00:00'
return 'T'.join((date_str, time_str))
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L167-L179
|
string to 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
|
string to date
|
python
|
def parse_date(value):
"""Parse one of the following date formats into a datetime object:
.. sourcecode:: text
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
If parsing fails the return value is `None`.
:param value: a string with a supported date format.
:return: a :class:`datetime.datetime` object.
"""
if value:
t = parsedate_tz(value.strip())
if t is not None:
try:
year = t[0]
# unfortunately that function does not tell us if two digit
# years were part of the string, or if they were prefixed
# with two zeroes. So what we do is to assume that 69-99
# refer to 1900, and everything below to 2000
if year >= 0 and year <= 68:
year += 2000
elif year >= 69 and year <= 99:
year += 1900
return datetime(*((year,) + t[1:7])) - timedelta(seconds=t[-1] or 0)
except (ValueError, OverflowError):
return None
|
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L780-L809
|
string to date
|
python
|
def _to_date_in_588(date_str):
"""
Convert date in the format ala 03.02.2017 to 3.2.2017.
Viz #100 for details.
"""
try:
date_tokens = (int(x) for x in date_str.split("."))
except ValueError:
return date_str
return ".".join(str(x) for x in date_tokens)
|
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/rest_api/to_output.py#L225-L236
|
string to date
|
python
|
def str2date(self, datestr):
"""Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default date template
try:
return datetime.strptime(
datestr, self.default_date_template).date()
except:
pass
# try every datetime templates
for template in DateTemplates:
try:
dt = datetime.strptime(datestr, template)
self.default_date_template = template
return dt.date()
except:
pass
# raise error
raise Exception("Unable to parse date from: %r" % datestr)
|
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L69-L109
|
string to date
|
python
|
def match_date(date):
"""Check if a string is a valid date
Args:
date(str)
Returns:
bool
"""
date_pattern = re.compile("^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])")
if re.match(date_pattern, date):
return True
return False
|
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/utils/date.py#L4-L17
|
string to 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
|
string to date
|
python
|
def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pyparsing.py#L6136-L6158
|
string to date
|
python
|
def calculate_date_strings(self, mode, numDays):
"""Returns a tuple of start (in YYYY-MM-DD format) and end date
strings (in YYYY-MM-DD HH:MM:SS format for an inclusive day)."""
yesterday = date.today() - timedelta(days=1)
endday = datetime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59, 999)
if mode:
startday = yesterday - timedelta(days=numDays)
else:
# daily mode
startday = yesterday
return startday.isoformat(), endday.strftime('%Y-%m-%d %H:%M:%S.%f')
|
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/intermittents_commenter/commenter.py#L172-L184
|
string to date
|
python
|
def to_date(ts: float) -> datetime.date:
"""Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2)
"""
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc).date()
|
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/datets.py#L34-L41
|
string to date
|
python
|
def parseDate(self, dateString, sourceTime=None):
"""
Parse short-form date strings::
'05/28/2006' or '04.21'
@type dateString: string
@param dateString: text to convert to a C{datetime}
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
@rtype: struct_time
@return: calculated C{struct_time} value of dateString
"""
if sourceTime is None:
yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
else:
yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime
# values pulled from regex's will be stored here and later
# assigned to mth, dy, yr based on information from the locale
# -1 is used as the marker value because we want zero values
# to be passed thru so they can be flagged as errors later
v1 = -1
v2 = -1
v3 = -1
accuracy = []
s = dateString
m = self.ptc.CRE_DATE2.search(s)
if m is not None:
index = m.start()
v1 = int(s[:index])
s = s[index + 1:]
m = self.ptc.CRE_DATE2.search(s)
if m is not None:
index = m.start()
v2 = int(s[:index])
v3 = int(s[index + 1:])
else:
v2 = int(s.strip())
v = [v1, v2, v3]
d = {'m': mth, 'd': dy, 'y': yr}
# yyyy/mm/dd format
dp_order = self.ptc.dp_order if v1 <= 31 else ['y', 'm', 'd']
for i in range(0, 3):
n = v[i]
c = dp_order[i]
if n >= 0:
d[c] = n
accuracy.append({'m': pdtContext.ACU_MONTH,
'd': pdtContext.ACU_DAY,
'y': pdtContext.ACU_YEAR}[c])
# if the year is not specified and the date has already
# passed, increment the year
if v3 == -1 and ((mth > d['m']) or (mth == d['m'] and dy > d['d'])):
yr = d['y'] + self.ptc.YearParseStyle
else:
yr = d['y']
mth = d['m']
dy = d['d']
# birthday epoch constraint
if yr < self.ptc.BirthdayEpoch:
yr += 2000
elif yr < 100:
yr += 1900
daysInCurrentMonth = self.ptc.daysInMonth(mth, yr)
debug and log.debug('parseDate: %s %s %s %s',
yr, mth, dy, daysInCurrentMonth)
with self.context() as ctx:
if mth > 0 and mth <= 12 and dy > 0 and \
dy <= daysInCurrentMonth:
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
ctx.updateAccuracy(*accuracy)
else:
# return current time if date string is invalid
sourceTime = time.localtime()
return sourceTime
|
https://github.com/bear/parsedatetime/blob/830775dc5e36395622b41f12317f5e10c303d3a2/parsedatetime/__init__.py#L394-L481
|
string to date
|
python
|
def parsehttpdate(string_):
"""
Parses an HTTP date into a datetime object.
>>> parsehttpdate('Thu, 01 Jan 1970 01:01:01 GMT')
datetime.datetime(1970, 1, 1, 1, 1, 1)
"""
try:
t = time.strptime(string_, "%a, %d %b %Y %H:%M:%S %Z")
except ValueError:
return None
return datetime.datetime(*t[:6])
|
https://github.com/talkincode/toughlib/blob/1c2f7dde3a7f101248f1b5f5d428cc85466995cf/toughlib/btforms/net.py#L126-L137
|
string to date
|
python
|
def parse_http_date(date: str) -> int:
"""
解析http时间到 timestamp
"""
try:
return int(
datetime.strptime(
date,
ISO_DATE_FORMAT,
).timestamp(),
)
except ValueError:
return 0
|
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L67-L79
|
string to date
|
python
|
def format_date(
self,
date: Union[int, float, datetime.datetime],
gmt_offset: int = 0,
relative: bool = True,
shorter: bool = False,
full_format: bool = False,
) -> str:
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July 10, 1980") with
``full_format=True``.
This method is primarily intended for dates in the past.
For dates in the future, we fall back to full format.
"""
if isinstance(date, (int, float)):
date = datetime.datetime.utcfromtimestamp(date)
now = datetime.datetime.utcnow()
if date > now:
if relative and (date - now).seconds < 60:
# Due to click skew, things are some things slightly
# in the future. Round timestamps in the immediate
# future down to now in relative mode.
date = now
else:
# Otherwise, future dates always use the full format.
full_format = True
local_date = date - datetime.timedelta(minutes=gmt_offset)
local_now = now - datetime.timedelta(minutes=gmt_offset)
local_yesterday = local_now - datetime.timedelta(hours=24)
difference = now - date
seconds = difference.seconds
days = difference.days
_ = self.translate
format = None
if not full_format:
if relative and days == 0:
if seconds < 50:
return _("1 second ago", "%(seconds)d seconds ago", seconds) % {
"seconds": seconds
}
if seconds < 50 * 60:
minutes = round(seconds / 60.0)
return _("1 minute ago", "%(minutes)d minutes ago", minutes) % {
"minutes": minutes
}
hours = round(seconds / (60.0 * 60))
return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours}
if days == 0:
format = _("%(time)s")
elif days == 1 and local_date.day == local_yesterday.day and relative:
format = _("yesterday") if shorter else _("yesterday at %(time)s")
elif days < 5:
format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s")
elif days < 334: # 11mo, since confusing for same month last year
format = (
_("%(month_name)s %(day)s")
if shorter
else _("%(month_name)s %(day)s at %(time)s")
)
if format is None:
format = (
_("%(month_name)s %(day)s, %(year)s")
if shorter
else _("%(month_name)s %(day)s, %(year)s at %(time)s")
)
tfhour_clock = self.code not in ("en", "en_US", "zh_CN")
if tfhour_clock:
str_time = "%d:%02d" % (local_date.hour, local_date.minute)
elif self.code == "zh_CN":
str_time = "%s%d:%02d" % (
(u"\u4e0a\u5348", u"\u4e0b\u5348")[local_date.hour >= 12],
local_date.hour % 12 or 12,
local_date.minute,
)
else:
str_time = "%d:%02d %s" % (
local_date.hour % 12 or 12,
local_date.minute,
("am", "pm")[local_date.hour >= 12],
)
return format % {
"month_name": self._months[local_date.month - 1],
"weekday": self._weekdays[local_date.weekday()],
"day": str(local_date.day),
"year": str(local_date.year),
"time": str_time,
}
|
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L323-L421
|
string to date
|
python
|
def _parse_date(string: str) -> datetime.date:
"""Parse an ISO format date (YYYY-mm-dd).
>>> _parse_date('1990-01-02')
datetime.date(1990, 1, 2)
"""
return datetime.datetime.strptime(string, '%Y-%m-%d').date()
|
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/migrations.py#L184-L190
|
string to date
|
python
|
def string_to_datetime(date):
"""Return a datetime.datetime instance with tzinfo.
I.e. a timezone aware datetime instance.
Acceptable formats for input are:
* 2012-01-10T12:13:14
* 2012-01-10T12:13:14.98765
* 2012-01-10T12:13:14.98765+03:00
* 2012-01-10T12:13:14.98765Z
* 2012-01-10 12:13:14
* 2012-01-10 12:13:14.98765
* 2012-01-10 12:13:14.98765+03:00
* 2012-01-10 12:13:14.98765Z
But also, some more odd ones (probably because of legacy):
* 2012-01-10
* ['2012-01-10', '12:13:14']
"""
if date is None:
return None
if isinstance(date, datetime.datetime):
if not date.tzinfo:
date = date.replace(tzinfo=UTC)
return date
if isinstance(date, list):
date = 'T'.join(date)
if isinstance(date, basestring):
if len(date) <= len('2000-01-01'):
return (datetime.datetime
.strptime(date, '%Y-%m-%d')
.replace(tzinfo=UTC))
else:
try:
parsed = isodate.parse_datetime(date)
except ValueError:
# e.g. '2012-01-10 12:13:14Z' becomes '2012-01-10T12:13:14Z'
parsed = isodate.parse_datetime(
re.sub('(\d)\s(\d)', r'\1T\2', date)
)
if not parsed.tzinfo:
parsed = parsed.replace(tzinfo=UTC)
return parsed
raise ValueError("date not a parsable string")
|
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/datetimeutil.py#L46-L91
|
string to date
|
python
|
def parseDate(dateString, strict=True):
"""
Return a datetime object, by parsing a string date/time
With strict=False, dateString may be None or '', otherwise it must be a
parseable string
"""
if (not strict) and (not dateString):
return None
if not isinstance(dateString, basestring):
raise TypeError('%r is not a string' % dateString)
return parser.parse(dateString)
|
https://github.com/corydodt/Codado/blob/487d51ec6132c05aa88e2f128012c95ccbf6928e/codado/py.py#L200-L213
|
string to date
|
python
|
def formatted_date(self, fmt: str = '', **kwargs) -> str:
"""Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date.
"""
date_obj = self.date(**kwargs)
if not fmt:
fmt = self._data['formats'].get('date')
return date_obj.strftime(fmt)
|
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L146-L159
|
string to date
|
python
|
def is_date(v) -> (bool, date):
"""
Boolean function for checking if v is a date
Args:
v:
Returns: bool
"""
if isinstance(v, date):
return True, v
try:
reg = r'^([0-9]{4})(?:-(0[1-9]|1[0-2])(?:-(0[1-9]|[1-2][0-9]|3[0-1])(?:T' \
r'([0-5][0-9])(?::([0-5][0-9])(?::([0-5][0-9]))?)?)?)?)?$'
match = re.match(reg, v)
if match:
groups = match.groups()
patterns = ['%Y', '%m', '%d', '%H', '%M', '%S']
d = datetime.strptime('-'.join([x for x in groups if x]),
'-'.join([patterns[i] for i in range(len(patterns)) if groups[i]]))
return True, d
except:
pass
return False, v
|
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/knowledge_graph_schema.py#L171-L194
|
string to date
|
python
|
def match_date(self, value, strict=False):
"""if value is a date"""
value = stringify(value)
try:
parse(value)
except Exception:
self.shout('Value %r is not a valid date', strict, value)
|
https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L43-L49
|
string to date
|
python
|
def str_to_datetime(ts):
"""Format a string to a datetime object.
This functions supports several date formats like YYYY-MM-DD,
MM-DD-YYYY, YY-MM-DD, YYYY-MM-DD HH:mm:SS +HH:MM, among others.
When the timezone is not provided, UTC+0 will be set as default
(using `dateutil.tz.tzutc` object).
:param ts: string to convert
:returns: a datetime object
:raises IvalidDateError: when the given string cannot be converted
on a valid date
"""
def parse_datetime(ts):
dt = dateutil.parser.parse(ts)
if not dt.tzinfo:
dt = dt.replace(tzinfo=dateutil.tz.tzutc())
return dt
if not ts:
raise InvalidDateError(date=str(ts))
try:
# Try to remove additional information after
# timezone section because it cannot be parsed,
# like in 'Wed, 26 Oct 2005 15:20:32 -0100 (GMT+1)'
# or in 'Thu, 14 Aug 2008 02:07:59 +0200 CEST'.
m = re.search(r"^.+?\s+[\+\-\d]\d{4}(\s+.+)$", ts)
if m:
ts = ts[:m.start(1)]
try:
dt = parse_datetime(ts)
except ValueError as e:
# Try to remove the timezone, usually it causes
# problems.
m = re.search(r"^(.+?)\s+[\+\-\d]\d{4}.*$", ts)
if m:
dt = parse_datetime(m.group(1))
logger.warning("Date %s str does not have a valid timezone", ts)
logger.warning("Date converted removing timezone info")
return dt
raise e
return dt
except ValueError as e:
raise InvalidDateError(date=str(ts))
|
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/datetime.py#L97-L148
|
string to date
|
python
|
def string_to_datetime(self, obj):
"""
Decode a datetime string to a datetime object
"""
if isinstance(obj, six.string_types) and len(obj) == 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) > 19:
try:
return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S.%f")
except ValueError:
pass
if isinstance(obj, six.string_types) and len(obj) == 10:
try:
return datetime.strptime(obj, "%Y-%m-%d")
except ValueError:
pass
return obj
|
https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/es.py#L127-L146
|
string to date
|
python
|
def dateFormat(when):
"""
Format the date when, e.g. Friday 14th of April 2011
"""
retval = ""
if when is not None:
dow = dateformat.format(when, "l")
dom = dateformat.format(when, "jS")
month = dateformat.format(when, "F")
if when.year != dt.date.today().year:
retval = _("{weekday} {day} of {month} {year}") \
.format(weekday=dow, day=dom, month=month, year=when.year)
else:
retval = _("{weekday} {day} of {month}") \
.format(weekday=dow, day=dom, month=month)
return retval
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L103-L118
|
string to date
|
python
|
def strpdate(string, format):
"""Parse the date string according to the format in `format`. Returns a
:class:`date` object. Internally, :meth:`datetime.strptime` is used to
parse the string and thus conversion specifiers for time fields (e.g. `%H`)
may be provided; these will be parsed but ignored.
Args:
string (str): The date string to be parsed.
format (str): The `strptime`_-style date format string.
Returns:
datetime.date
.. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> strpdate('2016-02-14', '%Y-%m-%d')
datetime.date(2016, 2, 14)
>>> strpdate('26/12 (2015)', '%d/%m (%Y)')
datetime.date(2015, 12, 26)
>>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S')
datetime.date(2015, 12, 31)
>>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f')
datetime.date(2016, 1, 1)
"""
whence = datetime.strptime(string, format)
return whence.date()
|
https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L253-L277
|
string to date
|
python
|
def deserialize_date(string):
"""
Deserializes string to date.
:param string: str.
:type string: str
:return: date.
:rtype: date
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
|
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/util.py#L257-L270
|
string to date
|
python
|
def parse_date(self, value):
"""A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if value is None:
raise Exception("Unable to parse date from %r" % value)
elif isinstance(value, string_types):
return self.str2date(value)
elif isinstance(value, int):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise Exception("Unable to parse date from %r" % value)
|
https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L158-L179
|
string to date
|
python
|
def format_date(self, value, format_):
"""
Format the date using Babel
"""
date_ = make_date(value)
return dates.format_date(date_, format_, locale=self.lang)
|
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L80-L85
|
string to date
|
python
|
def string_to_timestamp(timestring):
"""
Accepts a str, returns an int timestamp.
"""
ts = None
# Uses an extended version of Go's duration string.
try:
delta = durationpy.from_str(timestring);
past = datetime.datetime.utcnow() - delta
ts = calendar.timegm(past.timetuple())
return ts
except Exception as e:
pass
if ts:
return ts
# else:
# print("Unable to parse timestring.")
return 0
|
https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/utilities.py#L91-L111
|
string to date
|
python
|
def _date_by_len(self, string):
"""
Parses a date from a string based on its length
:param string:
A unicode string to parse
:return:
A datetime.datetime object, asn1crypto.util.extended_datetime object or
a unicode string
"""
strlen = len(string)
date_format = None
if strlen == 10:
date_format = '%Y%m%d%H'
elif strlen == 12:
date_format = '%Y%m%d%H%M'
elif strlen == 14:
date_format = '%Y%m%d%H%M%S'
elif strlen == 18:
date_format = '%Y%m%d%H%M%S.%f'
if date_format:
if len(string) >= 4 and string[0:4] == '0000':
# Year 2000 shares a calendar with year 0, and is supported natively
t = datetime.strptime('2000' + string[4:], date_format)
return extended_datetime(
0,
t.month,
t.day,
t.hour,
t.minute,
t.second,
t.microsecond,
t.tzinfo
)
return datetime.strptime(string, date_format)
return string
|
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/core.py#L4750-L4790
|
string to date
|
python
|
def date(self, col: str, **kwargs):
"""
Convert a column to date type
:param col: column name
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
:type \*\*kwargs: optional
:example: ``ds.date("mycol")``
"""
try:
self.df[col] = pd.to_datetime(self.df[col], **kwargs)
except Exception as e:
self.err(e, "Can not convert to date")
|
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/data/clean.py#L279-L293
|
string to date
|
python
|
def StringToUTCTime(time_string):
"""
Turns a DateTime string into UTC time.
:param time_string: Must be the format "MM/dd/yy hh:mm:ss"
:return: an integer representing the UTC int format
"""
szTime = c_char_p(time_string.encode('utf-8'))
res = dna_dll.StringToUTCTime(szTime)
return res
|
https://github.com/drericstrong/pyedna/blob/b8f8f52def4f26bb4f3a993ce3400769518385f6/pyedna/ezdna.py#L744-L753
|
string to date
|
python
|
def parse_date(date_string, ignoretz=True):
"""Parse a string as a date. If the string fails to parse, `None` will be returned instead
>>> parse_date('2017-08-15T18:24:31')
datetime.datetime(2017, 8, 15, 18, 24, 31)
Args:
date_string (`str`): Date in string format to parse
ignoretz (`bool`): If set ``True``, ignore time zones and return a naive :class:`datetime` object.
Returns:
`datetime`, `None`
"""
try:
return parser.parse(date_string, ignoretz=ignoretz)
except TypeError:
return None
|
https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/utils.py#L440-L456
|
string to date
|
python
|
def _date2int(date):
"""
Returns an integer representation of a date.
:param str|datetime.date date: The date.
:rtype: int
"""
if isinstance(date, str):
if date.endswith(' 00:00:00') or date.endswith('T00:00:00'):
# Ignore time suffix.
date = date[0:-9]
tmp = datetime.datetime.strptime(date, '%Y-%m-%d')
return tmp.toordinal()
if isinstance(date, datetime.date):
return date.toordinal()
if isinstance(date, int):
return date
raise ValueError('Unexpected type {0!s}'.format(date.__class__))
|
https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/helper/Type2Helper.py#L89-L110
|
string to date
|
python
|
def parse_date(date_str):
"""Parse elastic datetime string."""
if not date_str:
return None
try:
date = ciso8601.parse_datetime(date_str)
if not date:
date = arrow.get(date_str).datetime
except TypeError:
date = arrow.get(date_str[0]).datetime
return date
|
https://github.com/petrjasek/eve-elastic/blob/f146f31b348d22ac5559cf78717b3bb02efcb2d7/eve_elastic/elastic.py#L25-L36
|
string to date
|
python
|
def set_date(date):
'''
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_date 1/13/2016
'''
date_format = _get_date_time_format(date)
dt_obj = datetime.strptime(date, date_format)
cmd = 'systemsetup -setdate {0}'.format(dt_obj.strftime('%m:%d:%Y'))
return salt.utils.mac_utils.execute_return_success(cmd)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L78-L105
|
string to date
|
python
|
def datetime_to_str(date_time=None, str_format='%Y-%m-%d_%H:%M:%S.fff'):
"""
:param date_time: datetime of the date to convert to string
:param str_format: str of the format to return the string in
:return: str of the timestamp
"""
date_time = date_time or cst_now()
if DEFAULT_TIMEZONE_AWARE:
date_time += timedelta(hours=DEFAULT_TIMEZONE)
ret = date_time.strftime(str_format.split('.f')[0])
if '.f' in str_format:
sig_digits = len(str_format.split('.')[-1]) + 1
ret += str(date_time.microsecond / 1000000.0
)[1:].ljust(sig_digits, '0')[:sig_digits]
return ret
|
https://github.com/SeabornGames/Timestamp/blob/2b6902ddc2a009d6f3cb4dd0f6882bf4345f3871/seaborn_timestamp/timestamp.py#L97-L111
|
string to date
|
python
|
def _str_to_datetime(self, str_value):
"""Parses a `YYYY-MM-DD` string into a datetime object."""
try:
ldt = [int(f) for f in str_value.split('-')]
dt = datetime.datetime(*ldt)
except (ValueError, TypeError):
return None
return dt
|
https://github.com/jpscaletti/solution/blob/eabafd8e695bbb0209242e002dbcc05ffb327f43/solution/fields/splitted_datetime.py#L83-L90
|
string to 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
|
string to date
|
python
|
def parse_json_date(value):
"""
Parses an ISO8601 formatted datetime from a string value
"""
if not value:
return None
return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
|
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L50-L57
|
string to date
|
python
|
def _parse_date_perforce(aDateString):
"""parse a date in yyyy/mm/dd hh:mm:ss TTT format"""
# Fri, 2006/09/15 08:19:53 EDT
_my_date_pattern = re.compile( \
r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})')
m = _my_date_pattern.search(aDateString)
if m is None:
return None
dow, year, month, day, hour, minute, second, tz = m.groups()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
dateString = "%s, %s %s %s %s:%s:%s %s" % (dow, day, months[int(month) - 1], year, hour, minute, second, tz)
tm = rfc822.parsedate_tz(dateString)
if tm:
return time.gmtime(rfc822.mktime_tz(tm))
|
https://github.com/jmoiron/speedparser/blob/e7e8d79daf73b35c9259695ad1e379476e1dfc77/speedparser/feedparsercompat.py#L557-L571
|
string to date
|
python
|
def date_to_timestamp(date):
"""
date to unix timestamp in milliseconds
"""
date_tuple = date.timetuple()
timestamp = calendar.timegm(date_tuple) * 1000
return timestamp
|
https://github.com/telminov/sw-django-utils/blob/43b8491c87a5dd8fce145834c00198f4de14ceb9/djutils/date_utils.py#L39-L45
|
string to date
|
python
|
def FromTimeString(
cls, time_string, dayfirst=False, gmt_as_timezone=True,
timezone=pytz.UTC):
"""Converts a string containing a date and time value into a timestamp.
Args:
time_string: String that contains a date and time value.
dayfirst: An optional boolean argument. If set to true then the
parser will change the precedence in which it parses timestamps
from MM-DD-YYYY to DD-MM-YYYY (and YYYY-MM-DD will be
YYYY-DD-MM, etc).
gmt_as_timezone: Sometimes the dateutil parser will interpret GMT and UTC
the same way, that is not make a distinction. By default
this is set to true, that is GMT can be interpreted
differently than UTC. If that is not the expected result
this attribute can be set to false.
timezone: Optional timezone object (instance of pytz.timezone) that
the data and time value in the string represents. This value
is used when the timezone cannot be determined from the string.
Returns:
The timestamp which is an integer containing the number of micro seconds
since January 1, 1970, 00:00:00 UTC or 0 on error.
Raises:
TimestampError: if the time string could not be parsed.
"""
if not gmt_as_timezone and time_string.endswith(' GMT'):
time_string = '{0:s}UTC'.format(time_string[:-3])
try:
# TODO: deprecate the use of dateutil parser.
datetime_object = dateutil.parser.parse(time_string, dayfirst=dayfirst)
except (TypeError, ValueError) as exception:
raise errors.TimestampError((
'Unable to convert time string: {0:s} in to a datetime object '
'with error: {1!s}').format(time_string, exception))
if datetime_object.tzinfo:
datetime_object = datetime_object.astimezone(pytz.UTC)
else:
datetime_object = timezone.localize(datetime_object)
posix_time = int(calendar.timegm(datetime_object.utctimetuple()))
timestamp = posix_time * definitions.MICROSECONDS_PER_SECOND
return timestamp + datetime_object.microsecond
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/timelib.py#L268-L314
|
string to date
|
python
|
def inc_date(date_obj, num, date_fmt):
"""Increment the date by a certain number and return date object.
as the specific string format.
"""
return (date_obj + timedelta(days=num)).strftime(date_fmt)
|
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/utils.py#L107-L111
|
string to date
|
python
|
def parse_date(table_data):
"""
Static method that parses a given table data element with `Url.DATE_STRPTIME_FORMAT` and creates a `date` object from td's text contnet.
:param lxml.HtmlElement table_data: table_data tag to parse
:return: date object from td's text date
:rtype: datetime.date
"""
text = table_data.text.split('Added on ')
# Then it's 'Added today'. Hacky
if len(text) < 2:
return date.today()
# Looks like ['', 'Thursday, Mar 05, 2015']
return datetime.strptime(text[1], Parser.DATE_STRPTIME_FORMAT).date()
|
https://github.com/syndbg/demonoid-api/blob/518aa389ac91b5243b92fc19923103f31041a61e/demonoid/parser.py#L78-L91
|
string to date
|
python
|
def strptime(cls, date_string, fmt):
"""
This is opposite of the :py:meth:`khayyam.JalaliDate.strftime`,
and used to parse date strings into date object.
`ValueError` is raised if the date_string and format can’t be
parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a
complete list of formatting directives, see :doc:`/directives`.
:param date_string:
:param fmt:
:return: A :py:class:`khayyam.JalaliDate` corresponding to date_string, parsed according to format
:rtype: :py:class:`khayyam.JalaiDate`
"""
# noinspection PyUnresolvedReferences
result = cls.formatterfactory(fmt).parse(date_string)
result = {k: v for k, v in result.items() if k in ('year', 'month', 'day')}
return cls(**result)
|
https://github.com/pylover/khayyam/blob/7e3a30bb941f8dc8bad8bf9d3be2336fed04bb57/khayyam/jalali_date.py#L155-L173
|
string to date
|
python
|
def __deserialize_date(self, string):
"""
Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise ApiException(
status=0,
reason="Failed to parse `{0}` into a date object".format(string)
)
|
https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/api_client.py#L573-L589
|
string to date
|
python
|
def parse_date(string, force_datetime=False):
""" Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/"""
matches = DATE.match(string)
if not matches:
return None
values = dict([
(
k,
v if v[0] in '+-' else int(v)
) for k,v in matches.groupdict().items() if v and int(v)
])
if 'timestamp' in values:
value = datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(
hours=int(values.get('offset_h', 0)),
minutes=int(values.get('offset_m', 0)),
seconds=int(values['timestamp']) / 1000.0
)
return value
# I've made an assumption here, that a DateTime value will not
# ever be YYYY-MM-DDT00:00:00, which is probably bad. I'm not
# really sure how to handle this, other than to hard-code the
# names of the field that are actually Date rather than DateTime.
if len(values) > 3 or force_datetime:
return datetime.datetime(**values)
# Sometimes Xero returns Date(0+0000), so we end up with no
# values. Return None for this case
if not values:
return None
return datetime.date(**values)
|
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/utils.py#L64-L97
|
string to date
|
python
|
def timestring_to_datetime(timestring):
"""
Convert an ISO formated date and time string to a datetime object.
:param str timestring: String with date and time in ISO format.
:rtype: datetime
:return: datetime object
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UnicodeWarning)
result = dateutil_parser(timestring)
return result
|
https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L26-L38
|
string to date
|
python
|
def _get_expiration_date(cert):
'''
Returns a datetime.datetime object
'''
cert_obj = _read_cert(cert)
if cert_obj is None:
raise CommandExecutionError(
'Failed to read cert from {0}, see log for details'.format(cert)
)
return datetime.strptime(
salt.utils.stringutils.to_str(cert_obj.get_notAfter()),
four_digit_year_fmt
)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/tls.py#L612-L626
|
string to 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
|
string to date
|
python
|
def format_date_string(self, date_tuple):
"""
Receives a date_tuple object, and outputs a string
for placement in the article content.
"""
months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
date_string = ''
if date_tuple.season:
return '{0}, {1}'.format(date_tuple.season, date_tuple.year)
else:
if not date_tuple.month and not date_tuple.day:
return '{0}'.format(date_tuple.year)
if date_tuple.month:
date_string += months[int(date_tuple.month)]
if date_tuple.day:
date_string += ' ' + date_tuple.day
return ', '.join([date_string, date_tuple.year])
|
https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/__init__.py#L539-L556
|
string to date
|
python
|
def date_between(self, start_date='-30y', end_date='today'):
"""
Get a Date object based on a random date between two given dates.
Accepts date strings that can be recognized by strtotime().
:param start_date Defaults to 30 years ago
:param end_date Defaults to "today"
:example Date('1999-02-02')
:return Date
"""
start_date = self._parse_date(start_date)
end_date = self._parse_date(end_date)
return self.date_between_dates(date_start=start_date, date_end=end_date)
|
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1574-L1587
|
string to date
|
python
|
def n_day(date_string):
"""
date_string string in format "(number|a) day(s) ago"
"""
today = datetime.date.today()
match = re.match(r'(\d{1,3}|a) days? ago', date_string)
groups = match.groups()
if groups:
decrement = groups[0]
if decrement == 'a':
decrement = 1
return today - datetime.timedelta(days=int(decrement))
return None
|
https://github.com/askedrelic/journal/blob/848b8ec67ed124ec112926211ebeccbc8d11f2b0/journal/parse.py#L27-L39
|
string to date
|
python
|
def parse_date(datestring):
"""Attepmts to parse an ISO8601 formatted ``datestring``.
Returns a ``datetime.datetime`` object.
"""
datestring = str(datestring).strip()
if not datestring[0].isdigit():
raise ParseError()
if 'W' in datestring.upper():
try:
datestring = datestring[:-1] + str(int(datestring[-1:]) -1)
except:
pass
for regex, pattern in DATE_FORMATS:
if regex.match(datestring):
found = regex.search(datestring).groupdict()
dt = datetime.utcnow().strptime(found['matched'], pattern)
if 'fraction' in found and found['fraction'] is not None:
dt = dt.replace(microsecond=int(found['fraction'][1:]))
if 'timezone' in found and found['timezone'] is not None:
dt = dt.replace(tzinfo=Timezone(found.get('timezone', '')))
return dt
return parse_time(datestring)
|
https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L91-L120
|
string to date
|
python
|
def from_string(date_str):
"""
construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate:
"""
if date_str.count('-'):
str_format = '%Y-%m-%d'
elif date_str.count('.'):
str_format = '%d.%m.%Y'
elif date_str.count('/'):
str_format = '%m/%d/%Y'
elif len(date_str) == 8:
str_format = '%Y%m%d'
elif len(date_str) == 4:
year = ord(date_str[0]) * 256 + ord(date_str[1])
month = ord(date_str[2])
day = ord(date_str[3])
return BusinessDate.from_ymd(year, month, day)
else:
msg = "the date string " + date_str + " has not the right format"
raise ValueError(msg)
d = datetime.strptime(date_str, str_format)
return BusinessDate.from_ymd(d.year, d.month, d.day)
|
https://github.com/pbrisk/businessdate/blob/79a0c5a4e557cbacca82a430403b18413404a9bc/businessdate/businessdate.py#L205-L235
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.