Python datetime 模块,utcnow() 实例源码
我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用datetime.utcnow()。
def dueToday(self):
from dateutil import parser
from datetime import datetime
from datetime import timedelta
import pytz
today = datetime.utcnow().replace(tzinfo=pytz.UTC)
try:
wobble = parser.parse(self.__task_dict['due_date_utc']) - timedelta(hours=6) #that datetime thing is pulling todoist's due dates to my time zone
dueDate = wobble.date()
except:
dueDate = ""
if today.date() >= dueDate:
return 'Yes'
elif dueDate == "":
return "No due date"
else:
return 'No'
def dueLater(self):
from dateutil import parser
import datetime
import pytz
today = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
try:
wobble = parser.parse(self.__task_dict['due_date_utc'])
dueDate = wobble.date()
except:
dueDate = ""
if today.date() == dueDate:
return 'Yes'
elif dueDate == "":
return "No due date"
else:
return 'No'
def test_NaT_methods(self):
# GH 9513
raise_methods = ['astimezone', 'combine', 'ctime', 'dst',
'fromordinal', 'fromtimestamp', 'isocalendar',
'strftime', 'strptime', 'time', 'timestamp',
'timetuple', 'timetz', 'toordinal', 'tzname',
'utcfromtimestamp', 'utcnow', 'utcoffset',
'utctimetuple']
nat_methods = ['date', 'now', 'replace', 'to_datetime', 'today']
nan_methods = ['weekday', 'isoweekday']
for method in raise_methods:
if hasattr(NaT, method):
self.assertRaises(ValueError, getattr(NaT, method))
for method in nan_methods:
if hasattr(NaT, method):
self.assertTrue(np.isnan(getattr(NaT, method)()))
for method in nat_methods:
if hasattr(NaT, method):
self.assertIs(getattr(NaT, method)(), NaT)
# GH 12300
self.assertEqual(NaT.isoformat(), 'NaT')
def test_class_ops_pytz(self):
tm._skip_if_no_pytz()
from pytz import timezone
def compare(x, y):
self.assertEqual(int(Timestamp(x).value / 1e9),
int(Timestamp(y).value / 1e9))
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now('UTC'), datetime.now(timezone('UTC')))
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
compare(Timestamp.utcfromtimestamp(current_time),
datetime.utcfromtimestamp(current_time))
compare(Timestamp.fromtimestamp(current_time),
datetime.fromtimestamp(current_time))
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
compare(Timestamp.combine(date_component, time_component),
datetime.combine(date_component, time_component))
def test_class_ops_dateutil(self):
tm._skip_if_no_dateutil()
from dateutil.tz import tzutc
def compare(x, y):
self.assertEqual(int(np.round(Timestamp(x).value / 1e9)),
int(np.round(Timestamp(y).value / 1e9)))
compare(Timestamp.now(), datetime.now())
compare(Timestamp.now('UTC'), datetime.now(tzutc()))
compare(Timestamp.utcnow(), datetime.utcnow())
compare(Timestamp.today(), datetime.today())
current_time = calendar.timegm(datetime.now().utctimetuple())
compare(Timestamp.utcfromtimestamp(current_time),
datetime.utcfromtimestamp(current_time))
compare(Timestamp.fromtimestamp(current_time),
datetime.fromtimestamp(current_time))
date_component = datetime.utcnow()
time_component = (date_component + timedelta(minutes=10)).time()
compare(Timestamp.combine(date_component, time_component),
datetime.combine(date_component, time_component))
def __init__(self, *args, **kwargs):
"""
The constructor uses the ``dict()`` signature unmodified.
You can set the following manually or through a factory function:
* ``self.process`` an opaque value (to store the process that received or processed the message,
defaults to empty string).
* ``self.separator`` the default separator to use when parsing messages. Defaults to ``';'``
* ``self.time`` the time the message has been created or received. Defaults to ``datetime.utcnow()``
* ``self.recipient`` opaque value (to store for whom the message was intended)
* ``self.direction`` Whether the message was received (``0``), sent (``1``) or unknown (``None``)
* ``self.typed_values`` Whether the values in the message are typed. Defaults to ``False``
* ``self.codec`` Default :py:class:`~pyfixmsg.codec.stringfix.Codec` to use to parse message. Defaults
to a naive codec that doesn't support repeating groups
"""
self.process = ''
self.separator = ';'
self.time = datetime.datetime.utcnow()
self.recipient = ''
self.direction = None
self.typed_values = False
self.codec = Codec()
super(FixMessage, self).__init__(*args, **kwargs)
def beforeTodayString(days = 0, weeks = 0):
from datetime import datetime, timedelta
return (datetime.utcnow() - timedelta(days=days, weeks=weeks)).strftime('%Y-%m-%d')
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertIs(now.tzinfo, weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertIs(now.tzinfo, weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)
def _is_expired(self, host):
"""Check if the given host is considered to be expired.
Expiration is based on the value of HOST_TTL.
:param host: the host dictionary with check in info
:type: list(dict)
:returns: True if host entry expired, False otherwise
:rtype: bool
"""
last_check_in = host['last_check_in']
now = pytz.utc.localize(datetime.datetime.utcnow())
if not last_check_in.tzinfo:
last_check_in = pytz.utc.localize(last_check_in)
# datetime.now(tz.tzutc()) and datetime.utcnow() do not return a tz-aware datetime
# as a result, we use pytz to localize the timestamp to the UTC timezone
time_elapsed = (now - last_check_in).total_seconds()
if time_elapsed > settings.value.HOST_TTL:
logging.info(
"Expiring host %s for service %s because %d seconds have elapsed since last_checkin"
% (host['tags']['instance_id'], host['service'], time_elapsed)
)
return True
else:
return False
def clock():
from datetime import datetime #timestamp will be drawn and used for filenames
global timestamp
timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-4] #see function strftime in Python documentation
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertIs(now.tzinfo, weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertTrue(another.tzinfo is again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertTrue(now.tzinfo is weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)
def writeSearchRecord(lat, lng, key=None):
record = representation.geoRecordFromCoord(lat, lng)
from datetime import datetime
import time
now = datetime.utcnow()
record["timestamp"] = now.isoformat()
record["time"] = time.time()
db().child(searchesTable).update({ record["g"]: record })
def utcnow(cls):
"""Return a datetime object representing current time."""
result = cls._now()
return datetime_to_fakedatetime(result)
def utc_now() -> datetime.datetime:
"""
Return the current time for timezone UTC.
Unlike datetime.utcnow(), this timestamp is timezone-aware.
"""
return datetime.datetime.now(datetime.timezone.utc)
def makeTILL(till):
if(till is None):
from datetime import datetime
now = datetime.utcnow()
till = now.strftime("%Y-%m-%dT%H%M59.000000000Z")
return till
def getEvents(magnitude=1.0,significance=0,product='shakemap',lastUpdate=2678000):
"""
Return a list of earthquake event urls that meet the conditions set above.
Inputs:
* magnitude: Event magnitude (OR condition with significance)
* significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
* lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
* product: Only retrieve events that have this product type associated with them.
"""
fh = urllib2.urlopen(FEEDURL)
data = fh.read()
fh.close()
jdict = json.loads(data)
eventurls = []
tnow = datetime.utcnow()
for event in jdict['features']:
eurl = event['properties']['detail']
emag = event['properties']['mag']
esig = event['properties']['sig']
etypes = event['properties']['types'].split(',')[1:-1]
eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
hasproduct = product in etypes
if not hasproduct:
continue
if eupdate < tnow - timedelta(seconds=60*lastUpdate):
continue
eventurls.append(eurl)
return eventurls
def getEvents(magnitude=1.0,significance=0,product='dyfi',lastUpdate=2678000):
"""
Return a list of earthquake event urls that meet the conditions set above.
Inputs:
* magnitude: Event magnitude (OR condition with significance)
* significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
* lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
* product: Only retrieve events that have this product type associated with them.
"""
fh = urllib2.urlopen(FEEDURL)
data = fh.read()
fh.close()
jdict = json.loads(data)
eventurls = []
tnow = datetime.utcnow()
for event in jdict['features']:
eurl = event['properties']['detail']
emag = event['properties']['mag']
esig = event['properties']['sig']
etypes = event['properties']['types'].split(',')[1:-1]
eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
hasproduct = product in etypes
if not hasproduct:
continue
if eupdate < tnow - timedelta(seconds=60*lastUpdate):
continue
eventurls.append(eurl)
return eventurls
def getEvents(magnitude=1.0,significance=0,product='origin',lastUpdate=2678000):
"""
Return a list of earthquake event urls that meet the conditions set above.
Inputs:
* magnitude: Event magnitude (OR condition with significance)
* significance: Event significance (integer score assembled from weighting magnitude, PAGER alert level, Max MMI, etc.)
* lastUpdateDelta: Only retrieve events that have been updated in the past lastUpdate minutes.
* product: Only retrieve events that have this product type associated with them.
"""
fh = urllib2.urlopen(FEEDURL)
data = fh.read()
fh.close()
jdict = json.loads(data)
eventurls = []
tnow = datetime.utcnow()
for event in jdict['features']:
eurl = event['properties']['detail']
emag = event['properties']['mag']
esig = event['properties']['sig']
etypes = event['properties']['types'].split(',')[1:-1]
eupdate = datetime.utcfromtimestamp(event['properties']['updated']/1000)
hasproduct = product in etypes
if not hasproduct:
continue
if eupdate < tnow - timedelta(seconds=60*lastUpdate):
continue
eventurls.append(eurl)
return eventurls
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.utcnow()
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time, datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff / 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff / 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 14:
return "a week ago"
if day_diff < 31:
return str(day_diff / 7) + " weeks ago"
if day_diff < 62:
return "a month ago"
if day_diff < 365:
return str(day_diff / 30) + " months ago"
if day_diff < 730:
return "a year ago"
return str(day_diff / 365) + " years ago"
def test_constructor_explicit(self):
from datetime import datetime
span_id = 'test_span_id'
span_name = 'test_span_name'
parent_span = mock.Mock()
start_time = datetime.utcnow().isoformat() + 'Z'
end_time = datetime.utcnow().isoformat() + 'Z'
attributes = {
'/http/status_code': '200',
'/component': 'HTTP load balancer',
}
time_events = mock.Mock()
links = mock.Mock()
stack_trace = mock.Mock()
status = mock.Mock()
context_tracer = mock.Mock()
span = self._make_one(
name=span_name,
parent_span=parent_span,
attributes=attributes,
start_time=start_time,
end_time=end_time,
span_id=span_id,
stack_trace=stack_trace,
time_events=time_events,
links=links,
status=status,
context_tracer=context_tracer)
self.assertEqual(span.name, span_name)
self.assertEqual(span.span_id, span_id)
self.assertEqual(span.parent_span, parent_span)
self.assertEqual(span.attributes, attributes)
self.assertEqual(span.start_time, start_time)
self.assertEqual(span.end_time, end_time)
self.assertEqual(span.time_events, time_events)
self.assertEqual(span.stack_trace, stack_trace)
self.assertEqual(span.links, links)
self.assertEqual(span.status, status)
self.assertEqual(span.children, [])
self.assertEqual(span.context_tracer, context_tracer)