3

While researching a different approach to convert a timestamp like

2015-09-08 11:07:35

to

1441703255

I found a lot of pretty commonly found solutions use e.g.

date +%s --date "2015-09-08 11:07:35"

awk, perl or similiar solutions.

However SE conversion answer seems to use printf for that conversion on a "newer" bash version.

As this is to be used in a script with some limitations I rather not have to rely on date for that, but instead try an approach which might be faster. My relevant tries so far:

printf '%(%s)2015-09-08 11:07:35'
bash: printf: warning: `2': invalid time format specification

printf '%(%s)T' "2015-09-08 11:07:35"
bash: printf: 2015-09-08 11:07:35: invalid number

It seems I am unable to correctly use printf as I lack the exact manual where the dateformat string is described. The manpage and info coreutils 'printf invocation' did not help me solve this issue.

bash version is

bash --version
GNU bash, Version 4.3.11(1)-release (x86_64-pc-linux-gnu)
3
  • 4
    @don_crissti may as well make an answer out of that.
    – terdon
    Sep 8, 2015 at 11:51
  • @don_crissti thank you for confirming, i was afraid it is like that, please add this as answer, i will accept this after a day or so, if noone prooves us all wrong. Sep 8, 2015 at 12:02
  • 1
    printf '%(%s)T' "2015-09-08 11:07:35" works in ksh93, not bash. If you want a shell with strptime capability, your options are ksh93 and zsh. Sep 8, 2015 at 16:47

1 Answer 1

2

The other question specifically asks how to "get current time in seconds since the Epoch". The date format and arguments are described in the bash manual (scroll down to printf):

%(datefmt)T

Causes printf to output the date-time string resulting from using datefmt as a format string for strftime(3). The corresponding argument is an integer representing the number of seconds since the epoch. Two special argument values may be used: -1 represents the current time, and -2 represents the time the shell was invoked. If no argument is specified, conversion behaves as if -1 had been given. This is an exception to the usual printf behavior.

So the argument has to be an integer number of seconds since epoch¹ (e.g. see the answer to "How do I convert an epoch timestamp to a human readable format").


¹ Unless you use the special values (-1 or -2) or no argument (and in that case it defaults to -1)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .