Reputation: 101
I have a file "file_XYZ_18548". Here the name's ending 18548 is a timestamp in days, and it is changing day by day, like "file_XYZ_18550". I would like to get this date via variable but I couldn't find a date command to get the timestamp in days.
I can get the date result but I can't get the timestamp in reverse.
timeinday=18550
timestp=timeinday*86400
datetm=$(echo $timestp | gawk '{print(strftime("%Y-%m-%d %H:%M:%S", $0))}')
echo $datetm
2020-10-14 10:09:10
How can I get this with date command in bash scripting? Is there any way of this via awk/gawk etc..?
Upvotes: 0
Views: 356
Reputation: 753665
Given that 2020-10-14
- 18548
days corresponds to 1970-01-03
, it is reasonable to guess that the 'epoch' for the day count is 1970-01-01. It is likely that day 1 was 1970-01-01, so day zero was 1969-12-31.
You can use the GNU date
command like this:
daycount=18548
date -u -d "@$(( ($daycount-1) * 86400 ))" +"%Y-%m-%d %H:%M:%S"
That yields the result 2020-10-12 00:00:00
. You can drop the time component of the format if you wish (you probably do; midnight isn't very exciting when it is always midnight). You can calibrate the -1
to resolve exactly what day should correspond to 18548
. Just in case it isn't obvious, there are 86,400 seconds in a day (24 hours • 60 minutes per hour • 60 seconds per minute).
The $(( … ))
notation is Bash's Arithmetic Expansion notation.
If you want to convert the current time to the day offset, then you can use the %s
specifier to get the seconds since 1970-01-01 00:00:00Z and divide by 86400 to get the number of days:
echo $(( $(date +'%s') / 86400 ))
which (at 2020-10-14 23:30 -06:00, aka 1602739800 seconds since the Unix Epoch) yields the result:
18550
Again, if need be, you can adjust the value of the division to account for when day 1 was in this scheme. Shell arithmetic in Bash is integer arithmetic, which is exactly what is wanted. You might need to use -u
to get UTC as the time zone (as I did earlier), and so on.
Upvotes: 1