我正在尝试创建一个脚本,在为其提供开始和结束日期之后生成日期范围。
例如:
start = 2016-01-01
结束= 2017-10-01
脚本将输出如下列表:
['2016-01-01 2016-04-01',
2016-04-01 2016-07-01',
'2016-07-01 2016-10-01',
'2016-10-01 2017-01-01',
'2017-01-01 2017-04-01',
'2017-04-01 2017-07-01',
'2017-07-01 2017-10-01']
到目前为止,我已经设法生成了所有必要的时间范围,但是我无法将每个日期分组到这些时间范围所需的时间格式。
到目前为止,这是我的代码
start = '2016-01-01'
end = str(pd.to_datetime('today').replace(day=1))[:10]
dates = list(pd.date_range(start, end, freq="3MS"))
new_dates = []
for i in dates:
i= str(i)[:10]
new_dates.append(i)
输出: `
['2016-01-01',
'2016-04-01',
'2016-07-01',
'2016-10-01',
'2017-01-01',
'2017-04-01',
'2017-07-01',
'2017-10-01']
如果有人帮助我完成脚本的最后一部分,我非常感激。
答案 0 :(得分:1)
使用dates
数组,删除带dates[:-1]
的最后一个元素,删除第一个元素dates[1:]
,然后column_stack
两个数组:
import numpy as np
start = '2016-01-01'
end = pd.to_datetime('today').replace(day=1)
dates = pd.date_range(start, end, freq="3MS").strftime('%Y-%m-%d')
np.column_stack((dates[:-1], dates[1:]))
#array([['2016-01-01', '2016-04-01'],
# ['2016-04-01', '2016-07-01'],
# ['2016-07-01', '2016-10-01'],
# ['2016-10-01', '2017-01-01'],
# ['2017-01-01', '2017-04-01'],
# ['2017-04-01', '2017-07-01'],
# ['2017-07-01', '2017-10-01']],
# dtype='<U10')
要获得每个范围的条目,我们可以添加它们:
np.char.add(np.char.add(dates[:-1], ' '), dates[1:])
#array(['2016-01-01 2016-04-01', '2016-04-01 2016-07-01',
# '2016-07-01 2016-10-01', '2016-10-01 2017-01-01',
# '2017-01-01 2017-04-01', '2017-04-01 2017-07-01',
# '2017-07-01 2017-10-01'],
# dtype='<U21')
答案 1 :(得分:1)
添加numpy free替代
@property (strong, nonatomic) CNContactViewController *contactViewController;
@property (assign, nonatomic) UIBarStyle saveAppearanceBarStyle;
@property (strong, nonatomic) UIColor *saveAppearanceBarTintColor;
@property (strong, nonatomic) UIColor *saveAppearanceTintColor;
@property (strong, nonatomic) UIColor *saveAppearanceBackgroundColor;
@property (strong, nonatomic) NSDictionary<NSAttributedStringKey, id> * saveAppearanceTitleTextAttributes;
@property (assign, nonatomic) BOOL saveAppearanceTranslucent;
- (IBAction)onAddToContactsButtonTapped:(id)sender
self.contactViewController = [CNContactViewController viewControllerForUnknownContact: ... ]; // as before
[self suspendNavBarAppearanceSettings];
UINavigationController *popNav = [[UINavigationController alloc] initWithRootViewController:self.contactViewController];
popNav.modalPresentationStyle = UIModalPresentationPopover;
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onAddToContactsDoneTapped:)];
self.contactViewController.navigationItem.leftBarButtonItem = doneButton;
[self presentViewController:popNav animated:YES completion:nil];
UIPopoverPresentationController *popoverController = newNav.popoverPresentationController;
popoverController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popoverController.sourceRect = ...; // where you want it to point
popoverController.sourceView = ...; // where you want it to point
popoverController.delegate = self;
}
- (void) suspendNavBarAppearanceSettings
{
self.saveAppearanceBarStyle = [UINavigationBar appearance].barStyle;
self.saveAppearanceBarTintColor = [UINavigationBar appearance].barTintColor;
self.saveAppearanceTintColor = [UINavigationBar appearance].tintColor;
self.saveAppearanceBackgroundColor = [UINavigationBar appearance].backgroundColor;
self.saveAppearanceTitleTextAttributes = [UINavigationBar appearance].titleTextAttributes;
self.saveAppearanceTranslucent = [UINavigationBar appearance].translucent;
[UINavigationBar appearance].barStyle = UIBarStyleDefault;
[UINavigationBar appearance].barTintColor = nil;
[UINavigationBar appearance].tintColor = nil;
[UINavigationBar appearance].backgroundColor = nil;
[UINavigationBar appearance].titleTextAttributes = nil;
[UINavigationBar appearance].translucent = YES;
}
- (void) restoreNavBarAppearanceSettings
{
[UINavigationBar appearance].barStyle = self.saveAppearanceBarStyle;
[UINavigationBar appearance].barTintColor = self.saveAppearanceBarTintColor;
[UINavigationBar appearance].tintColor = self.saveAppearanceTintColor;
[UINavigationBar appearance].backgroundColor = self.saveAppearanceBackgroundColor;
[UINavigationBar appearance].titleTextAttributes = self.saveAppearanceTitleTextAttributes;
[UINavigationBar appearance].translucent = self.saveAppearanceTranslucent;
}
- (void)onAddToContactsDoneTapped:(id)sender
{
[self restoreNavBarAppearanceSettings];
[[self presentedViewController] dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - CNContactViewControllerDelegate
- (void)contactViewController:(CNContactViewController *)viewController
didCompleteWithContact:(nullable CNContact *)contact
{
[self restoreNavBarAppearanceSettings];
[[self presentedViewController] dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UIPopoverPresentationControllerDelegate
- (void)prepareForPopoverPresentation:(UIPopoverPresentationController *)popoverPresentationController
{
// This method is only called if we are presented in a popover, i.e. on iPad
// as opposed to full screen like on a phone.
// on iPad you just tap outside to finish, so remove the Done button
self.contactViewController.navigationItem.leftBarButtonItem = nil;
}
- (void)popoverPresentationControllerDidDismissPopover:(UIPopoverPresentationController *)popoverPresentationController
{
[self restoreNavBarAppearanceSettings];
}
这里需要注意的是,它的执行速度大约是@Psidom提供的第一个import pandas as pd
start = '2016-01-01'
end = pd.to_datetime('today').replace(day=1)
dates = pd.date_range(start, end, freq="3MS").strftime('%Y-%m-%d')
coupled_dates = []
for date in zip(*(dates[:-1], dates[1:])):
coupled_dates.append(' '.join(date))
coupled_dates
解决方案的两倍。当采取&#34; propper&#34;第二个版本,numpy
执行比python差3倍。
优势在于,如果您无法访问numpy
/ datetime
,则很可能会将此解决方案与标准pandas
模块一起使用。
答案 2 :(得分:1)
在分别删除第一个和最后一个元素后,您可以先将两个单独的列表合并到一个元组列表中(根据@Psidom的答案):
dates1 = dates[:-1]
dates2 = dates[1:]
这将生成两个列表,其中dates1
缺少原始列表中的最后一个元素,dates2
缺少原始列表的第一个元素。
dates3 = zip(dates1, dates2)
这将在dates3
中生成一个像这样的结构:
[('2016-01-01', '2016-04-01'), ('2016-04-01', '2016-07-01'), ...]
现在您可以生成所需输出字符串的列表,如下所示:
output = [x + ' ' + y for x,y in dates3]
您也可以将所有这些写入一行,但可能会损害可读性:
output = [x + ' ' + y for x,y in zip(dates[:-1], dates[1:])]
答案 3 :(得分:1)
import pandas as pd
a = pd.date_range("20160101","20171001", freq="3MS") # given date range
b =a.map(str).map(lambda x: x[:10]) # to_string and take 10 characters
c = b[:-1]+" "+b[1:] # shift the index array and join strings
d = c.tolist() # cast to python's list if you need