Get n days before now

本文介绍了一种使用毫秒计算日期偏移的方法,通过将时间转换为自1970年1月1日以来的毫秒数,可以轻松地进行日期计算,特别是对于大范围的日期操作更为有效。
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
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // 定义每月的最大天数 int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 判断是否为闰年 int is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 打印某个月的日历 void print_month_calendar(int year, int month, int start_day_of_week) { printf("\n %-15s\n", get_month_name(month)); printf("Su Mo Tu We Th Fr Sa\n"); int days_in_month = month_days[month - 1]; if (is_leap_year(year) && month == 2) { days_in_month++; } int day_counter = 1; for (int i = 0; i < start_day_of_week; i++) { printf(" "); } for (int i = start_day_of_week; i < 7; i++, day_counter++) { printf("%2d ", day_counter); } while (day_counter <= days_in_month) { printf("\n"); for (int i = 0; i < 7 && day_counter <= days_in_month; i++, day_counter++) { printf("%2d ", day_counter); } } printf("\n"); } // 获得月份名称 const char* get_month_name(int month) { const char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; return months[month - 1]; } // 计算给定日期距离今天的天数 long calculate_days_between_dates(struct tm date1, struct tm date2) { time_t t1 = mktime(&date1), t2 = mktime(&date2); long diff_seconds = difftime(t2, t1); return abs(diff_seconds / (60 * 60 * 24)); } // 主程序入口 int main() { time_t now = time(NULL); struct tm today = *localtime(&now); // 功能1:打印当前年历并标注今天 int current_year = today.tm_year + 1900; printf("Year Calendar of %d:\n", current_year); int first_day_of_year = ((current_year - 1) * 365 + (current_year - 1) / 4 - (current_year - 1) / 100 + (current_year - 1) / 400) % 7; for (int m = 1; m <= 12; m++) { int days_before_this_month = 0; for (int k = 1; k < m; k++) { days_before_this_month += month_days[k - 1]; } if (is_leap_year(current_year) && m >= 3) { days_before_this_month++; } int start_day_of_week = (first_day_of_year + days_before_this_month) % 7; print_month_calendar(current_year, m, start_day_of_week); } // 标记今天的日期 printf("Today's Date (%d-%02d-%02d):\n", current_year, today.tm_mon + 1, today.tm_mday); // 功能2:输入一个年份(1940-2040),输出该年的日历 int input_year; printf("Enter a year between 1940 and 2040 to display its calendar: "); scanf("%d", &input_year); if (input_year >= 1940 && input_year <= 2040) { printf("Calendar of Year %d:\n", input_year); int first_day_input_year = ((input_year - 1) * 365 + (input_year - 1) / 4 - (input_year - 1) / 100 + (input_year - 1) / 400) % 7; for (int m = 1; m <= 12; m++) { int days_before_this_month = 0; for (int k = 1; k < m; k++) { days_before_this_month += month_days[k - 1]; } if (is_leap_year(input_year) && m >= 3) { days_before_this_month++; } int start_day_of_week = (first_day_input_year + days_before_this_month) % 7; print_month_calendar(input_year, m, start_day_of_week); } } else { printf("Invalid year entered.\n"); } // 功能3:输入年月,输出对应月份的日历 int input_month; printf("Enter a year and month separated by space to display the corresponding month's calendar: "); scanf("%d%d", &input_year, &input_month); if (input_year >= 1940 && input_year <= 2040 && input_month >= 1 && input_month <= 12) { int first_day_input_year = ((input_year - 1) * 365 + (input_year - 1) / 4 - (input_year - 1) / 100 + (input_year - 1) / 400) % 7; int days_before_this_month = 0; for (int k = 1; k < input_month; k++) { days_before_this_month += month_days[k - 1]; } if (is_leap_year(input_year) && input_month >= 3) { days_before_this_month++; } int start_day_of_week = (first_day_input_year + days_before_this_month) % 7; print_month_calendar(input_year, input_month, start_day_of_week); } else { printf("Invalid input.\n"); } // 功能4:输入年月日,计算距今天有多少天、是星期几以及是否为公历节日 int input_day; printf("Enter a specific date as 'YYYY MM DD' to compute details about it: "); scanf("%d%d%d", &input_year, &input_month, &input_day); struct tm target_date = {0}; target_date.tm_year = input_year - 1900; target_date.tm_mon = input_month - 1; target_date.tm_mday = input_day; long days_diff = calculate_days_between_dates(target_date, today); int weekday_target = (today.tm_wday + days_diff) % 7; const char *weekdays[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; printf("The specified date is %ld days away from today.\n", days_diff); printf("It falls on a %s.\n", weekdays[weekday_target]); // 假设仅考虑元旦作为示例公历节日
05-27
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
ESC 27 # define CALENDAR_WIDTH 31 # define CALENDAR_HEIGHT 17 # define RED 1 # define GREEN 2 # define BLUE 3 # define YELLOW 4 # define WHITE 5 # define RED_COLOR (COLOR PAIR(RED) | A BOLD) # define GREEN_COLOR (COLOR PAIR(GREEN) | A BOLD) # define BLUE_COLOR (COLOR PAIR(BLUE) | A BOLD) # define YELLOW_COLOR (COLOR PAIR(YELLOW) | A BOLD) # define WHITE_COLOR (COLOR PAIR(WHITE) | A BOLD) # define GRAY_COLOR (COLOR PAIR(WHITE) | A NORMAL) typedef struct _date { int day; int month; int year; }date; void show_window(WINDOW* win);/*显示主界面*/ void show_calendar(WINDOW* calr);/*显示日历*/ void input_custom(WINDOW* win);/*用户输入年月*/ int is_leap(int year);/*判断闰年*/ int get_weekday(date d);/*取得日期的星期*/ date get_date before(date d, int n);/*取得日期d的前n天*/ date get_date after(date d, int n);/*取得日期d的后n天*/ int get_days(int year, int month);/*取得某年某月的天数*/ int day table[2][12] ={{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; char* WEEK[] ={" Sun", " Mon", " Tue", " Wen", " Thu", " Fri", " Sat"}; char* MONTH[] ={" January", " February", " March", " April", " May", " June", " July","ugust", " September", " October", " Nevember", " December"}; char* help[] = { " Press Up Down key to change year. ", " Press Left Right key to change month. ", " Press f key to show a custom calendar. ", " Press SPACE key to back to today. ", " Press ESC key to exit. ", 0 }; struct tm* today; date current; int main() {WINDOW* win = NULL; WINDOW* calr = NULL; int ch = ' ';long now; /*取得当前日期*/ time(& now); today = localtime(& now); initscr();/*初始化curses库*/ start color();/*允许使用颜色*/ cbreak();/*禁止行模式*/ noecho();/*禁止显示用户输入的字符*/ /*初始化颜色*/ init pair(RED, COLOR RED, COLOR BLACK); init pair(GREEN, COLOR GREEN, COLOR BLACK); init pair(BLUE, COLOR BLUE, COLOR BLACK); init pair(YELLOW, COLOR YELLOW, COLOR BLACK); init pair(WHITE, COLOR WHITE, COLOR BLACK); /*创建主窗口*/ win = newwin(LINES, COLS, 0, 0); /*创建一个自窗口显示日历*/ calr = derwin(win, CALENDAR HEIGHT, CALENDAR WIDTH,2,2); keypad(win, TRUE);/*允许使用控制键*/ while(ch != KEY ESC) { switch(ch) {case ' ':/*输入空格*/ current. day =1; current. month = today-> tm mon; current. year =1900+ today-> tm year; break; case 'f':/*输入“f”*/ input custom(win); break; case KEY UP:/*输入向上键*/ current. year--; break; case KEY DOWN:/*输入向下键*/ current. year++; break; case KEY LEFT:/*输入向左键*/ current. month--; if(current. month <0) { current. month =11; current. year--; } break; case KEY RIGHT:/*输入向右键*/ current. month++; if(current. month >11) { current. month =0; current. year++; } break; }show window(win);/*显示主窗口*/ show calendar(calr);/*显示日历窗口*/ wrefresh(win); ch = wgetch(win); } delwin(calr);/*释放日历窗口*/ delwin(win);/*释放主窗口*/ endwin();/*结束使用curses库*/ return 0; } void show window(WINDOW* win) { int row =1; int i =0; /*显示标题*/ wattron(win, BLUE COLOR I A UNDERLINE); mvwprintw(win, row++, CALENDAR WIDTH +3, "MY CALENDAR"); wattroff(win, BLUE COLOR | A UNDERLINE); /*显示帮助信息*/ row =4; for(i =0; help[i]; i++) { mvwprintw(win, row++, CALENDAR WIDTH +3, help[i]); row++; } /*显示今天的日期*/ wattron(win, GREEN COLOR | A UNDERLINE); mvwprintw(win, LINES -4, 2, " Today is %d-%d-%d\n",1900+ today-> tm year, today-> tm mon +1, today-> tm mday); wattroff(win, GREEN COLOR | A UNDERLINE); whline(win, '-', COLS); /*显示提示信息*/ wattron(win, BLUE COLOR); mvwprintw(win, LINES -2, 1, "> Press function key:"); wattroff(win, BLUE COLOR); /*设置边框*/ wborder(win, ' l ', ' l ', '=', '=', '+', '+', '+', '+') ; } void show calendar(WINDOW* calr) { int i =0; int x =1; int y =1; int wbegin = 0; date d; /*显示年、月信息*/ wattron(calr, YELLOW COLOR); mvwprintw(calr, 1, 2, "%s %d\n ", MONTH[current. month],urrent. year); wattroff(calr, YELLOW COLOR); whline(calr, '-', CALENDAR WIDTH); /*显示星期*/ y = 3; x = 1; for(i = 0; i < 7; ++i) { if(i == 0 || i == 6) { wattron(calr, RED COLOR); mvwprintw(calr, y, x, "%4s", WEEK[i]); wattroff(calr, RED COLOR); } else { wattron(calr, BLUE COLOR); mvwprintw(calr, y, x, "%4s", WEEK[i]); wattroff(calr, BLUE COLOR); } x += 4; } /*显示日历*/ wbegin = get weekday(current); d = get date before(current, wbegin); for(i = 0; i < 42; ++i) { y = 5+2* ((int)(i /7)); x = 1 + (i %7) *4; if (d. day == today-> tm mday && d. month == today-> tm mon && d. year == (1900 + today-> tm year)) { wateron(calr, GREEN COLOR); mvwprintw(calr, y, x, "%4d", d. day); wattroff(calr, GREEN COLOR); } else if (d. month != current. month) { wattron(calr, GRAY COLOR); mvwprintw(calr, y, x, "%4d", d. day); wattroff(calr, GRAY COLOR); } else if ((i %7) ==0 11(i %7) ==6) { wattron(calr, RED COLOR); mvwprintw(calr, y, x, "%4d", d. day); wattroff(calr, RED COLOR); } else { wattron(calr, WHITE COLOR); mvwprintw(calr, y, x, "%4d", d. day); wattroff(calr, WHITE COLOR); } d = get date after(d, 1); } /*设置边框*/ wborder(calr, ' l', ' l ', '-', '-', '+', '+', '+', '+'); } void input custom(WINDOW* win) { int year =0; int month =0; wattron(win, GREEN COLOR); mvwprintw(win, LINES - 2, 1, "> Input year/ month(example:2000/1):"); wattroff(win, GREEN COLOR); nocbreak(); echo(); if (wscanw(win, "%d/%d", & year, & month) ==2&& month >0 && month<13) { current. year = year; current. month = month -1; } else { wattron(win, RED COLOR); mvwprintw(win, LINES - 2, 1, "> Input error:"); wrefresh(win); sleep(2); wattroff(win,·RED COLOR); } mvwprintw(win, LINES -2, 1, ""); whline(win, ' ', COLS-2); cbreak(); noecho(); } int is leap(int year) { if (((year%4==0) && (year%100 !=0)) || (year%400==0)) { return 1; } return 0; } int get weekday(date d) { int w=0; int y = d. year %100; int c = d. year / 100; int m = d. month >1? (d. month +1) : (d. month +13); w = y + y /4+ c /4-2* c +26* (m +1) /10+ d. day -1; while (w <0) { w +=70; } return (w % 7); } date get date before(date d, int n) { date bd = d; while(n > 0) { n--; bd. day--; if(bd. day <1) { bd. month--; if(bd. month < 0) { bd. year--; bd. month =11; } bd. day = get days(bd. year, bd. month); } } return bd; } date get date after(date d, int n) { date ad = d; int max = get_days(ad.year, ad.month); while(n >0) { n--; ad. day++; if (ad.day > max) ad. month++; if (ad. month >11) { ad. year++; ad. month =0; } ad. day =1; max = get dayslad. year, ad. month); return ad; } int get_days(int year, int month) { return day_table[is_leap(year)][month]; }
06-09
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值