Get n days before now

本文介绍了一种使用毫秒计算日期偏移的方法,通过将时间转换为自1970年1月1日以来的毫秒数,可以轻松地进行日期计算,特别是对于大范围的日期操作更为有效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When I tried to google  and get a way to get a Date() n days before now.
Lots of the answer are trying to do with Calendar.set() or GregorianCalendar.roll().
When n > 30, enven > 366, the solution becomes complex.
The easier way for me is calculating with milliseconds since January 1, 1970, 00:00:00 GMT.

A groovy example:
What you have to care for this way is the value of milliseconds is large.
For example, the value of milliseconds of 50days is more than 32-bit unsiged.
But the good news is that the value of milliseconds of 100years is less than 43-bit unsigned.

import java.util.Date

def now = new Date()
def nowMsFrom1970 = now.getTime()
def days = 32
def MsInOneDay = 24*3600*1000

def days_before = now.clone()
days_before.setTime(nowMsFrom1970 - (long)days * MsInOneDay)

log.info(now.format("YYYY-MM-dd HH:mm:ss"))
log.info("Day before " + days.toString() + " days:")
log.info(days_before.format("YYYY-MM-dd HH:mm:ss"))

result:
Thu Aug 23 22:38:18 CST 2012:INFO:2012-08-23 22:38:18
Thu Aug 23 22:38:18 CST 2012:INFO:Day before 32 days:
Thu Aug 23 22:38:18 CST 2012:INFO:2012-07-22 22:38:18
from jqdata import * import pandas as pd import numpy as np from jqfactor import get_factor_values def initialize(context): set_option("avoid_future_data", True) g.hold_days = 0 g.profit_target = 1.1 # 止盈比例 g.stop_loss = 0.95 # 止损比例 run_daily(select, time='before_open') run_daily(trade_stocks, time='14:30') def select(context): stocks = get_index_stocks('000016.XSHG') valid_stocks = [s for s in stocks if not is_st_stock(s, context.previous_date)] if valid_stocks: kdj_data = get_kdj(valid_stocks, check_date=context.previous_date) g.buy_list = [s for s in kdj_data if kdj_data[s][2] > kdj_data[s][0] and kdj_data[s][0] > kdj_data[s][1] and kdj_data[s][1] < 20] g.hold_days = 0 else: g.buy_list = [] def trade_stocks(context): positions = context.portfolio.positions for stock in list(positions.keys()): # 使用get_price获取最新收盘价 current_price_data = get_price(stock, end_date=context.now, frequency='daily', fields=['close'], count=1) if not current_price_data.empty: current_price = current_price_data['close'].iloc[-1] else: logger.warning(f"No price data available for stock {stock}. Skipping...") continue buy_price = positions[stock].avg_cost if current_price >= buy_price * g.profit_target or current_price <= buy_price * g.stop_loss or g.hold_days >= 5: order_target(stock, 0) if g.buy_list and g.hold_days < 5: cash_per_stock = context.portfolio.available_cash / len(g.buy_list) for stock in g.buy_list: if stock not in positions: order_value(stock, cash_per_stock) g.hold_days += 1 def get_kdj(securities, check_date, N=9, M1=3, M2=3): kdj_dict = {} for stock in securities: try: price_data = get_price(stock, end_date=check_date, frequency='daily', fields=['close'], fq='pre', count=N) if not price_data.empty: close_prices = price_data['close'].dropna().values if len(close_prices) >= N: low_list = close_prices[-N:] high_list = close_prices[-N:] rsv = (close_prices[-1] - min(low_list)) / (max(high_list) - min(low_list)) * 100 if max(high_list) != min(low_list) else 0 k = 50 if 'k' not in locals() else 1 / 3 * rsv + 2 / 3 * k d = 50 if 'd' not in locals() else 1 / 3 * k + 2 / 3 * d j = 3 * k - 2 * d kdj_dict[stock] = (k, d, j) except Exception as e: logger.error(f"Error calculating KDJ for stock {stock}: {e}") return kdj_dict def is_st_stock(stock, date): try: st_data = get_extras('is_st', stock, end_date=date, count=1) return st_data[stock][0] if stock in st_data else False except Exception as e: logger.error(f"Error checking ST status for stock {stock}: {e}") return False Traceback (most recent call last): File "/tmp/jqcore/jqboson/jqboson/api/objects/ctx.py", line 91, in __getattr__ return getattr(self.__backend_ctx, attr) AttributeError: '_StrategyContextBackend' object has no attribute 'now' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/jqcore/jqboson/jqboson/core/entry.py", line 379, in _run engine.start() File "/tmp/jqcore/jqboson/jqboson/core/engine.py", line 246, in start self._dispatcher.start() File "/tmp/jqcore/jqboson/jqboson/core/dispatcher.py", line 280, in start self._run_loop() File "/tmp/jqcore/jqboson/jqboson/core/dispatcher.py", line 240, in _run_loop self._loop.run() File "/tmp/jqcore/jqboson/jqboson/core/loop/loop.py", line 120, in run self._handle_queue() File "/tmp/jqcore/jqboson/jqboson/core/loop/loop.py", line 166, in _handle_queue message.callback(**message.callback_data) File "/tmp/jqcore/jqboson/jqboson/core/dispatcher.py", line 110, in callback self._event_bus.emit(evt) File "/tmp/jqcore/jqboson/jqboson/core/bus.py", line 47, in emit ret.append(call(event)) File "/tmp/jqcore/jqboson/jqboson/core/strategy.py", line 433, in _wrapper return cb(self._context.strategy_environment.strategy_context, **cb_kwargs) File "/tmp/strategy/user_code.py", line 28, in trade_stocks current_price_data = get_price(stock, end_date=context.now, frequency='daily', fields=['close'], count=1) File "/tmp/jqcore/jqboson/jqboson/api/objects/ctx.py", line 94, in __getattr__ (self.__class__.__name__, attr)) AttributeError: 'StrategyContext' object has no attribute 'now' 根据这个代码这个问题怎么解决
06-15
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值