def timestampFromString(value):
return calendar.timegm(time.strptime(value)) - epoch_diff
python类timegm()的实例源码
def default(self, obj):
try:
if isinstance(obj, datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
millis = int(
calendar.timegm(obj.timetuple()) * 1000 +
obj.microsecond / 1000
)
return millis
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
def nsdate_from_python_date(date):
# TODO: Find a way to get a timestamp from python date without the calendar module
date_as_tuple = date.timetuple()
timestamp = pysyscal.timegm(date_as_tuple)
return NSDate.alloc().initWithTimeIntervalSince1970_(timestamp)
def from_datetime(cls, generation_time):
"""Create a dummy ObjectId instance with a specific generation time.
This method is useful for doing range queries on a field
containing :class:`ObjectId` instances.
.. warning::
It is not safe to insert a document containing an ObjectId
generated using this method. This method deliberately
eliminates the uniqueness guarantee that ObjectIds
generally provide. ObjectIds generated with this method
should be used exclusively in queries.
`generation_time` will be converted to UTC. Naive datetime
instances will be treated as though they already contain UTC.
An example using this helper to get documents where ``"_id"``
was generated before January 1, 2010 would be:
>>> gen_time = datetime.datetime(2010, 1, 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)
>>> result = collection.find({"_id": {"$lt": dummy_id}})
:Parameters:
- `generation_time`: :class:`~datetime.datetime` to be used
as the generation time for the resulting ObjectId.
"""
if generation_time.utcoffset() is not None:
generation_time = generation_time - generation_time.utcoffset()
timestamp = calendar.timegm(generation_time.timetuple())
oid = struct.pack(
">i", int(timestamp)) + b"\x00\x00\x00\x00\x00\x00\x00\x00"
return cls(oid)
def __init__(self, time, inc):
"""Create a new :class:`Timestamp`.
This class is only for use with the MongoDB opLog. If you need
to store a regular timestamp, please use a
:class:`~datetime.datetime`.
Raises :class:`TypeError` if `time` is not an instance of
:class: `int` or :class:`~datetime.datetime`, or `inc` is not
an instance of :class:`int`. Raises :class:`ValueError` if
`time` or `inc` is not in [0, 2**32).
:Parameters:
- `time`: time in seconds since epoch UTC, or a naive UTC
:class:`~datetime.datetime`, or an aware
:class:`~datetime.datetime`
- `inc`: the incrementing counter
"""
if isinstance(time, datetime.datetime):
if time.utcoffset() is not None:
time = time - time.utcoffset()
time = int(calendar.timegm(time.timetuple()))
if not isinstance(time, integer_types):
raise TypeError("time must be an instance of int")
if not isinstance(inc, integer_types):
raise TypeError("inc must be an instance of int")
if not 0 <= time < UPPERBOUND:
raise ValueError("time must be contained in [0, 2**32)")
if not 0 <= inc < UPPERBOUND:
raise ValueError("inc must be contained in [0, 2**32)")
self.__time = time
self.__inc = inc
def _encode_datetime(name, value, dummy0, dummy1):
"""Encode datetime.datetime."""
if value.utcoffset() is not None:
value = value - value.utcoffset()
millis = int(calendar.timegm(value.timetuple()) * 1000 +
value.microsecond / 1000)
return b"\x09" + name + _PACK_LONG(millis)
def test_times_from_uuid1(self):
node = uuid.getnode()
now = time.time()
u = uuid.uuid1(node, 0)
t = util.unix_time_from_uuid1(u)
self.assertAlmostEqual(now, t, 2)
dt = util.datetime_from_uuid1(u)
t = calendar.timegm(dt.timetuple()) + dt.microsecond / 1e6
self.assertAlmostEqual(now, t, 2)
def cql_encode_datetime(self, val):
"""
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
with millisecond precision.
"""
timestamp = calendar.timegm(val.utctimetuple())
return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3))
def _from_timetuple(self, t):
self.days_from_epoch = calendar.timegm(t) // Date.DAY
def interpret_datestring(val):
if val[-5] in ('+', '-'):
offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1')
val = val[:-5]
else:
offset = -time.timezone
for tformat in cql_timestamp_formats:
try:
tval = time.strptime(val, tformat)
except ValueError:
continue
# scale seconds to millis for the raw value
return (calendar.timegm(tval) + offset) * 1e3
else:
raise ValueError("can't interpret %r as a date" % (val,))
def toUnixSeconds(timestruct):
"""Convert a datetime struct to a Unix timestamp in seconds.
:type timestruct: :any:`datetime.datetime`
:param timestruct: A ``datetime`` object to convert into a timestamp in
Unix Era seconds.
:rtype: int
"""
return calendar.timegm(timestruct)
def intervalStart(self, when=0):
"""Get the start time of the interval that contains **when**.
:param int when: The time which we're trying to determine the start of
interval that contains it. This should be given in Unix seconds,
for example, taken from :func:`calendar.timegm`.
:rtype: int
:returns: The Unix epoch timestamp for the start time of the interval
that contains **when**.
"""
# Convert `when`s which are floats, i.e. from time.time(), to ints:
when = int(math.ceil(when))
if self.intervalPeriod == 'month':
# For months, we always start at the beginning of the month.
date = fromUnixSeconds(when)
months = (date.year * 12) + (date.month - 1)
months -= (months % self.intervalCount)
month = months % 12 + 1
return toUnixSeconds((months // 12, month, 1, 0, 0, 0))
elif self.intervalPeriod == 'day':
# For days, we start at the beginning of a day.
when -= when % (86400 * self.intervalCount)
return when
elif self.intervalPeriod == 'hour':
# For hours, we start at the beginning of an hour.
when -= when % (3600 * self.intervalCount)
return when
elif self.intervalPeriod == 'minute':
when -= when % (60 * self.intervalCount)
return when
elif self.intervalPeriod == 'second':
when -= when % self.intervalCount
return when
def getInterval(self, when=0):
"""Get the interval that contains the time **when**.
>>> import calendar
>>> from farfetchd.schedule import ScheduledInterval
>>> sched = ScheduledInterval(1, 'month')
>>> when = calendar.timegm((2007, 12, 12, 0, 0, 0))
>>> sched.getInterval(when)
'2007-12'
>>> then = calendar.timegm((2014, 05, 13, 20, 25, 13))
>>> sched.getInterval(then)
'2014-05'
:param int when: The time which we're trying to find the corresponding
interval for. Given in Unix seconds, for example, taken from
:func:`calendar.timegm`.
:rtype: str
:returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
specificity depends on what type of interval we're using. For
example, if using ``"month"``, the return value would be something
like ``"2013-12"``.
"""
date = fromUnixSeconds(self.intervalStart(when))
fstr = "%04Y-%02m"
if self.intervalPeriod != 'month':
fstr += "-%02d"
if self.intervalPeriod != 'day':
fstr += " %02H"
if self.intervalPeriod != 'hour':
fstr += ":%02M"
if self.intervalPeriod == 'minute':
fstr += ":%02S"
return date.strftime(fstr)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def datetime_to_header(dt):
return formatdate(calendar.timegm(dt.timetuple()))
def update_headers(self, resp):
headers = resp.headers
if 'expires' in headers:
return {}
if 'cache-control' in headers and headers['cache-control'] != 'public':
return {}
if resp.status not in self.cacheable_by_default_statuses:
return {}
if 'date' not in headers or 'last-modified' not in headers:
return {}
date = calendar.timegm(parsedate_tz(headers['date']))
last_modified = parsedate(headers['last-modified'])
if date is None or last_modified is None:
return {}
now = time.time()
current_age = max(0, now - date)
delta = date - calendar.timegm(last_modified)
freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
if freshness_lifetime <= current_age:
return {}
expires = date + freshness_lifetime
return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))}
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def tuple_to_secs(tuple):
""" Convert time tuple to UTC seconds. """
return calendar.timegm(tuple)
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.
Returns:
The time this status message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))
def GetCreatedAtInSeconds(self):
'''Get the time this direct message was posted, in seconds since the epoch.
Returns:
The time this direct message was posted, in seconds since the epoch.
'''
return calendar.timegm(rfc822.parsedate(self.created_at))