TransWikia.com

GNU date: truncate provided date-time and set provided hours

Unix & Linux Asked by basin on November 23, 2021

I have a timestamp value in a variable and I need to truncate the hours from it and set different hours. Can GNU date do this in one go? It definitely does this for special dates like "today", "tomorrow" or "yesterday", but I can’t make it use arithmetic with arbitrary timestamp:

$ date -d"tomorrow 10:05"
Thu Jul 23 10:05:00     2020

il@mar2 ~
$ date -d"yesterday 10:05"
Tue Jul 21 10:05:00     2020

$ date -d"@1595413447"
Wed Jul 22 13:24:07     2020

il@mar2 ~
$ date -d"@1595413447 10:05"
date: invalid date '@1595413447 10:05'
# desired: Wed Jul 22 10:05:00     2020

2 Answers

You can always specify the time as part of the output format:

$ date -d @1595413447 '%a %b %e 10:05:00    %Y'
Wed Jul 22 10:05:00    2020

Or more portably (avoiding the GNU date dependency) in the ksh93 shell:

$ printf '%(%a %b %e 10:05:00    %Y)Tn' '#1595413447'
Wed Jul 22 10:05:00    2020

Though ksh93 also supports:

$ printf '%(%a %b %e %T    %Y)Tn' '#1595413447 10:05'
Wed Jul 22 10:05:00    2020

Or in the zsh shell:

$ zmodload zsh/datetime
$ strftime '%a %b %e 10:05:00    %Y' 1595413447
Wed Jul 22 10:05:00    2020

Or in the bash shell (bash copied ksh93's printf %T for formatting but not for date parsing):

$ printf '%(%a %b %e 10:05:00    %Y)Tn' 1595413447
Wed Jul 22 10:05:00    2020

Answered by Stéphane Chazelas on November 23, 2021

GNU date doesn't allow any additional specifications to a timestamp.

From the date info documentation:

If you precede a number with ‘@’, it represents an internal timestamp as a count of seconds. The number can contain an internal decimal point (either ‘.’ or ‘,’); any excess precision not supported by the internal representation is truncated toward minus infinity. Such a number cannot be combined with any other date item, as it specifies a complete timestamp.

(emphasis mine)

I'm afraid you need two invocations, such as

date -d "$(date -d @1595413447 +'%F 10:05')"

Answered by Freddy on November 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP