How to Find Out the Date of the Last Saturday in Linux Shell Script or Python

How to find out the date of the last Saturday in Linux shell script or python?

$ date +"%b-%d-%Y" -d "last saturday"
Jul-13-2013

How to use bash to get the last day of each month for the current year without using if else or switch or while loop?

my take:

for m in {1..12}; do
date -d "$m/1 + 1 month - 1 day" "+%b - %d days";
done

To explain: for the first iteration when m=1 the -d argument is "1/1 + 1 month - 1 day" and "1/1" is interpreted as Jan 1st. So Jan 1 + 1 month - 1 day is Jan 31. Next iteration "2/1" is Feb 1st, add a month subtract a day to get Feb 28 or 29. And so on.

Print a file's last modified date in Bash

You can use the
stat
command

stat -c %y "$entry"

More info


%y time of last modification, human-readable

In a unix shell, how to get yesterday's date into a variable?

If you have Perl available (and your date doesn't have nice features like yesterday), you can use:

pax> date
Thu Aug 18 19:29:49 XYZ 2010

pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;')

pax> echo $dt
17/08/2010

How to loop through dates using Bash?

Using GNU date:

d=2015-01-01
while [ "$d" != 2015-02-20 ]; do
echo $d
d=$(date -I -d "$d + 1 day")

# mac option for d decl (the +1d is equivalent to + 1 day)
# d=$(date -j -v +1d -f "%Y-%m-%d" $d +%Y-%m-%d)
done

Note that because this uses string comparison, it requires full ISO 8601 notation of the edge dates (do not remove leading zeros). To check for valid input data and coerce it to a valid form if possible, you can use date as well:

# slightly malformed input data
input_start=2015-1-1
input_end=2015-2-23

# After this, startdate and enddate will be valid ISO 8601 dates,
# or the script will have aborted when it encountered unparseable data
# such as input_end=abcd
startdate=$(date -I -d "$input_start") || exit -1
enddate=$(date -I -d "$input_end") || exit -1

d="$startdate"
while [ "$d" != "$enddate" ]; do
echo $d
d=$(date -I -d "$d + 1 day")
done

One final addition: To check that $startdate is before $enddate, if you only expect dates between the years 1000 and 9999, you can simply use string comparison like this:

while [[ "$d" < "$enddate" ]]; do

To be on the very safe side beyond the year 10000, when lexicographical comparison breaks down, use

while [ "$(date -d "$d" +%Y%m%d)" -lt "$(date -d "$enddate" +%Y%m%d)" ]; do

The expression $(date -d "$d" +%Y%m%d) converts $d to a numerical form, i.e., 2015-02-23 becomes 20150223, and the idea is that dates in this form can be compared numerically.

How to check if today is Monday in Python

You can use date.weekday() like this:

from datetime import date

# If today is Monday (aka 0 of 6), then run the report
if date.today().weekday() == 0:
run_report()


Related Topics



Leave a reply



Submit