Skip to content

Instantly share code, notes, and snippets.

@besserwisser
Last active March 7, 2023 07:30
Show Gist options
  • Save besserwisser/66e64b1824af4a4133ddd2eb0bfeabd7 to your computer and use it in GitHub Desktop.
Save besserwisser/66e64b1824af4a4133ddd2eb0bfeabd7 to your computer and use it in GitHub Desktop.
Get display on/off timestamps and differences (macos, zsh, per day)
# zsh function to get the first display on time and the last display off time of the day
# Also shows difference time difference between those both
# installation: put this function in your .zshrc file
# reload zshrc: source ~/.zshrc
# use it like this for today: when
# use it like this for yesterday: when 1
# use it like this for the day before yesterday: when 2
when() {
if ! [[ -z $1 || $1 =~ '^[0-9]+$' ]]; then
print "Usage: when [pastDayOffset]"
print "Use no argument or argument must be a number."
return
fi
pastDayOffset="0"
if [[ -n $1 ]]; then
pastDayOffset=$1
fi
endTimestamp=$(date +"%Y-%m-%d %H:%M:%S")
offsettedDate=$(date -v-"$pastDayOffset"d +"%Y-%m-%d")
startLine=$(pmset -g log | grep "$offsettedDate.*Display is turned on" | head -n 1)
startTimestamp=$(echo $startLine | cut -c 1-19)
if [[ -n $1 ]]; then
endLine=$(pmset -g log | grep "$offsettedDate.*Display is turned off" | tail -n 1)
endTimestamp=$(echo $endLine | cut -c 1-19)
fi
print "\nstart time: $startTimestamp"
print "end time: $endTimestamp\n"
startTimestampInSeconds=$(date -j -f "%Y-%m-%d %H:%M:%S" "$startTimestamp" +%s)
endInSeconds=$(date -j -f "%Y-%m-%d %H:%M:%S" "$endTimestamp" +%s)
difference="$(($endInSeconds - $startTimestampInSeconds))"
humanReadableDifference=$(date -u -r $difference +"%T")
printf "Time from first display on to last display off: $(tput setaf 5)$humanReadableDifference\n\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment