Python datetime.now() Examples
The following are 30
code examples of datetime.now().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
datetime
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: inventory.py From project-dev-kpis with MIT License | 6 votes |
def observe_inventory(owner, repo_name, pulls): for metric in ['additions', 'commits', 'deletions']: metric_sum = None if len(pulls) > 0: metric_sum = sum([getattr(p, metric) for p in pulls]) else: metric_sum = 0 logger.info( 'Observed for owner "%s", repo "%s", %d %s' % (owner, repo_name, metric_sum, metric)) CODE_INVENTORY.labels(owner, repo_name, metric).set(metric_sum) for pull in pulls: days_old = weekdays_between(pull.created_at, datetime.now()) logger.info( 'Observed for owner "%s", repo "%s", %.2f days old PR' % (owner, repo_name, days_old)) CODE_INVENTORY_AGE.labels(owner, repo_name).observe(days_old)
Example #2
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_astimezone(self): # Pretty boring! The TZ test is more interesting here. astimezone() # simply can't be applied to a naive object. dt = self.theclass.now() f = FixedOffset(44, "") self.assertRaises(TypeError, dt.astimezone) # not enough args self.assertRaises(TypeError, dt.astimezone, f, f) # too many args self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type self.assertRaises(ValueError, dt.astimezone, f) # naive self.assertRaises(ValueError, dt.astimezone, tz=f) # naive class Bogus(tzinfo): def utcoffset(self, dt): return None def dst(self, dt): return timedelta(0) bog = Bogus() self.assertRaises(ValueError, dt.astimezone, bog) # naive class AlsoBogus(tzinfo): def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return None alsobog = AlsoBogus() self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
Example #3
Source File: feedgenerator.py From bioforum with MIT License | 6 votes |
def latest_post_date(self): """ Return the latest item's pubdate or updateddate. If no items have either of these attributes this return the current UTC date/time. """ latest_date = None date_keys = ('updateddate', 'pubdate') for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc)
Example #4
Source File: test_lib.py From dataflows with MIT License | 6 votes |
def test_load_dates_timezones(): from dataflows import Flow, checkpoint from datetime import datetime, timezone import shutil dates = [ datetime.now(), datetime.now(timezone.utc).astimezone() ] shutil.rmtree('.checkpoints/test_load_dates_timezones', ignore_errors=True) Flow( [{'date': d.date(), 'datetime': d} for d in dates], checkpoint('test_load_dates_timezones') ).process() results = Flow( checkpoint('test_load_dates_timezones') ).results() assert list(map(lambda x: x['date'], results[0][0])) == \ list(map(lambda x: x.date(), dates)) assert list(map(lambda x: x['datetime'], results[0][0])) == \ list(map(lambda x: x, dates))
Example #5
Source File: test_freezegun.py From pytest-freezegun with MIT License | 6 votes |
def test_class_just_fixture(testdir): testdir.makepyfile(""" from datetime import datetime import time class TestAsClass(object): def test_just_fixture(self, freezer): now = datetime.now() time.sleep(0.1) later = datetime.now() assert now == later """) result = testdir.runpytest('-v', '-s') assert result.ret == 0
Example #6
Source File: test_datetime.py From BinderFilter with MIT License | 6 votes |
def test_astimezone(self): # Pretty boring! The TZ test is more interesting here. astimezone() # simply can't be applied to a naive object. dt = self.theclass.now() f = FixedOffset(44, "") self.assertRaises(TypeError, dt.astimezone) # not enough args self.assertRaises(TypeError, dt.astimezone, f, f) # too many args self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type self.assertRaises(ValueError, dt.astimezone, f) # naive self.assertRaises(ValueError, dt.astimezone, tz=f) # naive class Bogus(tzinfo): def utcoffset(self, dt): return None def dst(self, dt): return timedelta(0) bog = Bogus() self.assertRaises(ValueError, dt.astimezone, bog) # naive class AlsoBogus(tzinfo): def utcoffset(self, dt): return timedelta(0) def dst(self, dt): return None alsobog = AlsoBogus() self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
Example #7
Source File: test_freezegun.py From pytest-freezegun with MIT License | 6 votes |
def test_freezing_time_in_fixture(testdir): testdir.makepyfile(""" import pytest from datetime import date, datetime @pytest.fixture def today(): return datetime.now().date() @pytest.mark.freeze_time('2017-05-20 15:42') def test_sth(today): assert today == date(2017, 5, 20) """) result = testdir.runpytest('-v', '-s') assert result.ret == 0
Example #8
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
def test_normal(self): fo = FixedOffset(3, "Three") self.assertIsInstance(fo, tzinfo) for dt in datetime.now(), None: self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) self.assertEqual(fo.tzname(dt), "Three") self.assertEqual(fo.dst(dt), timedelta(minutes=42))
Example #9
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
def test_subclass_must_override(self): class NotEnough(tzinfo): def __init__(self, offset, name): self.__offset = offset self.__name = name self.assertTrue(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") self.assertIsInstance(ne, tzinfo) dt = datetime.now() self.assertRaises(NotImplementedError, ne.tzname, dt) self.assertRaises(NotImplementedError, ne.utcoffset, dt) self.assertRaises(NotImplementedError, ne.dst, dt)
Example #10
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
def test_roundtrip(self): for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7), self.theclass.now()): # Verify dt -> string -> datetime identity. s = repr(dt) self.assertTrue(s.startswith('datetime.')) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) # Verify identity via reconstructing from pieces. dt2 = self.theclass(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond) self.assertEqual(dt, dt2)
Example #11
Source File: service.py From vnpy_crypto with MIT License | 5 votes |
def trade_off(): """检查现在是否为非交易时间""" now = datetime.now() a = datetime.now().replace(hour=2, minute=35, second=0, microsecond=0) b = datetime.now().replace(hour=8, minute=55, second=0, microsecond=0) c = datetime.now().replace(hour=15, minute=30, second=0, microsecond=0) d = datetime.now().replace(hour=20, minute=55, second=0, microsecond=0) weekend = (now.isoweekday() == 6 and now >= a) or (now.isoweekday() == 7) or(now.isoweekday() == 1 and now <= a) off = (a<= now <= b) or (c <= now <= d) or weekend return off
Example #12
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
def test_more_astimezone(self): # The inherited test_astimezone covered some trivial and error cases. fnone = FixedOffset(None, "None") f44m = FixedOffset(44, "44") fm5h = FixedOffset(-timedelta(hours=5), "m300") dt = self.theclass.now(tz=f44m) self.assertTrue(dt.tzinfo is f44m) # Replacing with degenerate tzinfo raises an exception. self.assertRaises(ValueError, dt.astimezone, fnone) # Ditto with None tz. self.assertRaises(TypeError, dt.astimezone, None) # Replacing with same tzinfo makes no change. x = dt.astimezone(dt.tzinfo) self.assertTrue(x.tzinfo is f44m) self.assertEqual(x.date(), dt.date()) self.assertEqual(x.time(), dt.time()) # Replacing with different tzinfo does adjust. got = dt.astimezone(fm5h) self.assertTrue(got.tzinfo is fm5h) self.assertEqual(got.utcoffset(), timedelta(hours=-5)) expected = dt - dt.utcoffset() # in effect, convert to UTC expected += fm5h.utcoffset(dt) # and from there to local time expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo self.assertEqual(got.date(), expected.date()) self.assertEqual(got.time(), expected.time()) self.assertEqual(got.timetz(), expected.timetz()) self.assertTrue(got.tzinfo is expected.tzinfo) self.assertEqual(got, expected)
Example #13
Source File: test_datetime.py From BinderFilter with MIT License | 5 votes |
def test_bogus_dst(self): class ok(tzinfo): def utcoffset(self, dt): return HOUR def dst(self, dt): return HOUR now = self.theclass.now().replace(tzinfo=utc_real) # Doesn't blow up. now.astimezone(ok()) # Does blow up. class notok(ok): def dst(self, dt): return None self.assertRaises(ValueError, now.astimezone, notok())
Example #14
Source File: test_timeseries.py From Computable with MIT License | 5 votes |
def test_set_dataframe_column_ns_dtype(self): x = DataFrame([datetime.now(), datetime.now()]) self.assert_(x[0].dtype == np.dtype('M8[ns]'))
Example #15
Source File: test_timeseries.py From Computable with MIT License | 5 votes |
def test_stringified_slice_with_tz(self): #GH2658 import datetime start=datetime.datetime.now() idx=DatetimeIndex(start=start,freq="1d",periods=10) df=DataFrame(lrange(10),index=idx) df["2013-01-14 23:44:34.437768-05:00":] # no exception here
Example #16
Source File: bot.py From csb with GNU Affero General Public License v3.0 | 5 votes |
def returnTime(): timeInput = droptime.split(":") tarHour = int(timeInput[0]) tarMin = int(timeInput[1]) tarSec = int(timeInput[2]) target = datetime.now() target = target.replace(hour=tarHour, minute=tarMin, second=tarSec) while True: cur = datetime.now() if cur >= target: clock.sleep(1) break
Example #17
Source File: client.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def restart(self, timeout=None): """Restarts this Splunk instance. The service is unavailable until it has successfully restarted. If a *timeout* value is specified, ``restart`` blocks until the service resumes or the timeout period has been exceeded. Otherwise, ``restart`` returns immediately. :param timeout: A timeout period, in seconds. :type timeout: ``integer`` """ result = self.post("server/control/restart") if timeout is None: return result start = datetime.now() diff = timedelta(seconds=10) while datetime.now() - start < diff: try: self.login() # Has the server gone down yet? sleep(0.3) except Exception: break # Server is down. Move on. start = datetime.now() diff = timedelta(seconds=timeout) while datetime.now() - start < diff: try: self.login() # Awake yet? return result except Exception, e: sleep(2)
Example #18
Source File: test_freezegun.py From pytest-freezegun with MIT License | 5 votes |
def test_freezing_time(testdir): testdir.makepyfile(""" import pytest from datetime import date, datetime @pytest.mark.freeze_time('2017-05-20 15:42') def test_sth(): assert datetime.now().date() == date(2017, 5, 20) """) result = testdir.runpytest('-v', '-s') assert result.ret == 0
Example #19
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_bogus_dst(self): class ok(tzinfo): def utcoffset(self, dt): return HOUR def dst(self, dt): return HOUR now = self.theclass.now().replace(tzinfo=utc_real) # Doesn't blow up. now.astimezone(ok()) # Does blow up. class notok(ok): def dst(self, dt): return None self.assertRaises(ValueError, now.astimezone, notok())
Example #20
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_more_astimezone(self): # The inherited test_astimezone covered some trivial and error cases. fnone = FixedOffset(None, "None") f44m = FixedOffset(44, "44") fm5h = FixedOffset(-timedelta(hours=5), "m300") dt = self.theclass.now(tz=f44m) self.assertIs(dt.tzinfo, f44m) # Replacing with degenerate tzinfo raises an exception. self.assertRaises(ValueError, dt.astimezone, fnone) # Ditto with None tz. self.assertRaises(TypeError, dt.astimezone, None) # Replacing with same tzinfo makes no change. x = dt.astimezone(dt.tzinfo) self.assertIs(x.tzinfo, f44m) self.assertEqual(x.date(), dt.date()) self.assertEqual(x.time(), dt.time()) # Replacing with different tzinfo does adjust. got = dt.astimezone(fm5h) self.assertIs(got.tzinfo, fm5h) self.assertEqual(got.utcoffset(), timedelta(hours=-5)) expected = dt - dt.utcoffset() # in effect, convert to UTC expected += fm5h.utcoffset(dt) # and from there to local time expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo self.assertEqual(got.date(), expected.date()) self.assertEqual(got.time(), expected.time()) self.assertEqual(got.timetz(), expected.timetz()) self.assertIs(got.tzinfo, expected.tzinfo) self.assertEqual(got, expected)
Example #21
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_roundtrip(self): for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7), self.theclass.now()): # Verify dt -> string -> datetime identity. s = repr(dt) self.assertTrue(s.startswith('datetime.')) s = s[9:] dt2 = eval(s) self.assertEqual(dt, dt2) # Verify identity via reconstructing from pieces. dt2 = self.theclass(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond) self.assertEqual(dt, dt2)
Example #22
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_normal(self): fo = FixedOffset(3, "Three") self.assertIsInstance(fo, tzinfo) for dt in datetime.now(), None: self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) self.assertEqual(fo.tzname(dt), "Three") self.assertEqual(fo.dst(dt), timedelta(minutes=42))
Example #23
Source File: test_datetime.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_subclass_must_override(self): class NotEnough(tzinfo): def __init__(self, offset, name): self.__offset = offset self.__name = name self.assertTrue(issubclass(NotEnough, tzinfo)) ne = NotEnough(3, "NotByALongShot") self.assertIsInstance(ne, tzinfo) dt = datetime.now() self.assertRaises(NotImplementedError, ne.tzname, dt) self.assertRaises(NotImplementedError, ne.utcoffset, dt) self.assertRaises(NotImplementedError, ne.dst, dt)
Example #24
Source File: make_xlsx.py From aws-cost-report with MIT License | 5 votes |
def snapshots_summary(workbook, header_format, val_format): def transform(x): try: if x == "": return 0.0 else: return float(x) except ValueError: return x with open(IN_SNAPSHOT_USAGE_LAST_MONTH) as f: reader = csv.DictReader(f) worksheet = workbook.add_worksheet("Snapshots last month") last_month = datetime.now() + dateutil.relativedelta.relativedelta(months=-1) worksheet.merge_range("A1:C1", "Snapshots for {}-{:02d}".format(last_month.year, last_month.month), header_format) cur_format = workbook.add_format() cur_format.set_align("center") cur_format.set_align("vcenter") cur_format.set_border() cur_format.set_num_format(NUMFORMAT_CURRENCY) worksheet.freeze_panes(2, 0) worksheet.set_column(0, 0, 25) worksheet.set_column(1, 1, 80) worksheet.set_column(2, 2, 25) refs = { "Account": [0, "Account", str, val_format], "ResourceId": [1, "Resource Id", str, val_format], "Cost": [2, "Cost", transform, cur_format], } for v in refs.values(): worksheet.write(1, v[0], v[1], header_format) for i, line in zip(itertools.count(2), reader): for h, v in line.items(): worksheet.write(i, refs[h][0], refs[h][2](v), refs[h][3])
Example #25
Source File: make_xlsx.py From aws-cost-report with MIT License | 5 votes |
def ebs_summary(workbook, header_format, val_format): def transform(x): try: if x == "": return 0.0 else: return float(x) except ValueError: return x with open(IN_EBS_USAGE_LAST_MONTH) as f: reader = csv.DictReader(f) worksheet = workbook.add_worksheet("EBS last month") last_month = datetime.now() + dateutil.relativedelta.relativedelta(months=-1) worksheet.merge_range("A1:F1", "EBS for {}-{:02d}".format(last_month.year, last_month.month), header_format) worksheet.merge_range("A2:A3", "Account", header_format) worksheet.merge_range("B2:B3", "Resource ID", header_format) worksheet.merge_range("C2:C3", "Region", header_format) worksheet.merge_range("D2:D3", "Cost", header_format) worksheet.merge_range("E2:F2", "Instance Linked", header_format) cur_format = workbook.add_format() cur_format.set_align("center") cur_format.set_align("vcenter") cur_format.set_border() cur_format.set_num_format(NUMFORMAT_CURRENCY) worksheet.freeze_panes(3, 0) worksheet.set_column(0, len(reader.fieldnames)-1, 25) refs = { "Account": [0, "Account", str, val_format], "ResourceId": [1, "Resource Id", str, val_format], "Region": [2, "Region", str, val_format], "Cost": [3, "Cost", transform, cur_format], "InstanceId": [4, "ID", str, val_format], "InstanceName": [5, "Name", str, val_format], } for v in refs.values(): worksheet.write(2, v[0], v[1], header_format) for i, line in zip(itertools.count(3), reader): for h, v in line.items(): worksheet.write(i, refs[h][0], refs[h][2](v), refs[h][3])
Example #26
Source File: test_lib.py From dataflows with MIT License | 5 votes |
def test_save_load_dates(): from dataflows import Flow, dump_to_path, load, set_type, printer import datetime Flow( [{'id': 1, 'ts': datetime.datetime.now()}, {'id': 2, 'ts': datetime.datetime.now()}], set_type('ts', type='datetime', format='%Y-%m-%d/%H:%M:%S'), dump_to_path('out/test_save_load_dates') ).process() res, _, _ = Flow( load('out/test_save_load_dates/datapackage.json'), printer() ).results()
Example #27
Source File: test_lib.py From dataflows with MIT License | 5 votes |
def test_load_dates(): # from dateutil.tz import tzutc from dataflows import Flow, dump_to_path, load, set_type, ValidationError, exceptions import datetime _today = datetime.date.today() _now = datetime.datetime.now() def run_flow(datetime_format=None): Flow( [{'today': str(_today), 'now': str(_now)}], set_type('today', type='date'), set_type('now', type='datetime', format=datetime_format), dump_to_path('out/dump_dates') ).process() with pytest.raises(exceptions.ProcessorError) as excinfo: run_flow() assert isinstance(excinfo.value.cause, ValidationError) # Default is isoformat(), str() gives a slightly different format: # >>> from datetime import datetime # >>> n = datetime.now() # >>> str(n) # '2018-11-22 13:25:47.945209' # >>> n.isoformat() # '2018-11-22T13:25:47.945209' run_flow(datetime_format='%Y-%m-%d %H:%M:%S.%f') out_now = datetime.datetime(_now.year, _now.month, _now.day, _now.hour, _now.minute, _now.second) assert Flow( load('out/dump_dates/datapackage.json'), ).results()[0] == [[{'today': _today, 'now': out_now}]]
Example #28
Source File: client.py From SplunkForPCAP with MIT License | 5 votes |
def touch(self): """Extends the expiration time of the search to the current time (now) plus the time-to-live (ttl) value. :return: The :class:`Job`. """ self.post("control", action="touch") return self
Example #29
Source File: client.py From SplunkForPCAP with MIT License | 5 votes |
def search(self, query, **kwargs): """Runs a search using a search query and any optional arguments you provide, and returns a `Job` object representing the search. :param query: A search query. :type query: ``string`` :param kwargs: Arguments for the search (optional): * "output_mode" (``string``): Specifies the output format of the results. * "earliest_time" (``string``): Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. * "latest_time" (``string``): Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. * "rf" (``string``): Specifies one or more fields to add to the search. :type kwargs: ``dict`` :rtype: class:`Job` :returns: An object representing the created job. """ return self.jobs.create(query, **kwargs)
Example #30
Source File: client.py From SplunkForPCAP with MIT License | 5 votes |
def restart(self, timeout=None): """Restarts this Splunk instance. The service is unavailable until it has successfully restarted. If a *timeout* value is specified, ``restart`` blocks until the service resumes or the timeout period has been exceeded. Otherwise, ``restart`` returns immediately. :param timeout: A timeout period, in seconds. :type timeout: ``integer`` """ msg = { "value": "Restart requested by " + self.username + "via the Splunk SDK for Python"} # This message will be deleted once the server actually restarts. self.messages.create(name="restart_required", **msg) result = self.post("/services/server/control/restart") if timeout is None: return result start = datetime.now() diff = timedelta(seconds=timeout) while datetime.now() - start < diff: try: self.login() if not self.restart_required: return result except Exception, e: sleep(1)