简体   繁体   English

Shell脚本在Linux中获取日期

[英]Shell Script to Get Date In Linux

I am new to Shell scripting. 我是Shell脚本的新手。

I want to write a script to get any random Date from the user in the format YYYY:MM:DD and echo (display) date of tuesday and friday of previous week. 我想编写一个脚本,以从用户那里获取任何随机的Date,格式为YYYY:MM:DD并回显(显示)星期二的星期二和星期五的日期。

For Example if I give Input Date as 2013-12-11 . 例如,如果我输入日期为2013-12-11
The output should be 输出应为

date1= 2013-12-06
date2= 2013-12-10

or 要么

Input Date as 2013-12-07 输入日期为2013-12-07

Output 产量

date1= 2013-12-03
date2= 2013-12-06

Try the following: 请尝试以下操作:

input=2013-12-11
lastTues=$(date -d "$input -$(date -d "$input +5 days" +%u) days" +%Y-%m-%d)
lastFri=$(date -d "$input -$(date -d "$input +2 days" +%u) days" +%Y-%m-%d)

This command first works out how many days there are between the input date and last Tuesday (or Friday), call this X . 此命令首先计算输入日期与上一个星期二(或星期五)之间有多少天,称为X It then runs date -d "inputDate -X days" to calculate the new date. 然后,它运行date -d "inputDate -X days"以计算新日期。

Perl to the rescue: Perl解救:

#!/usr/bin/perl
use warnings;
use strict;

use DateTime;

sub tuefri {
    my ($year, $month, $day) = split /[^0-9]/, shift;
    my $date = 'DateTime'->new( year  => $year,
                                month => $month,
                                day   => $day,
                              );
    $date->subtract(days => 7);
    my @result;
    until (2 == @result) {
        push @result, $date->ymd if grep $_ == $date->day_of_week, 2, 5;
        $date->add(days => 1);
    }
    return @result
}

my $i = 1;
print 'date', $i++, "= $_\n" for tuefri(shift);

A solution using the python-dateutil module: 使用python-dateutil模块的解决方案:

import fileinput
from dateutil.relativedelta import TU, FR, relativedelta
from datetime import date

for line in fileinput.input():
    d = date(*(map(int, line.rstrip().split('-'))))
    print(d + relativedelta(weekday=FR(-1)))
    print(d + relativedelta(weekday=TU(-1)))

Run it like: 像这样运行:

python script.py <<<"2013-12-11"

That yields: 产生:

2013-12-06
2013-12-10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM