Given a commit with the date Mon Aug 18 21:05:38 2014 +0200
, how can I get the Unix timestamp of it in seconds?
The following command produces a number that discards the number (presumably because the timezone information of date
got discarded):
$ hg log -l1 --template '{date(date, "%s")}\n'
1408392338
$ date -d@1408392338
Mon Aug 18 22:05:38 CEST 2014
I am effectively looking for the equivalent of the git
command that produces the commit date as a Unix timestamp:
git log -n1 --pretty=%ct
The simplest solution is to take the first field produced from the template format {date|hgdate}
, which is already in UTC. The second field in this format just gives the timezone, and can be discarded by applying Mercurial's word
function within the format specifier. Here is a test of this format against the system date
command and your own (correct, but longer) answer, on Mercurial 3.7.3:
$ date +%s && hg commit -m 'ok'
1539258496
$ TZ=UTC hg log -l1 --template '{date(date|localdate, "%s")}\n'
1539258496
$ hg log -l1 -r. --template '{date|hgdate}'
1539258496 -7200
$ hg log -l1 --template '{word(0, date|hgdate)}'
1539258496
The correctness is also confirmed by the description in the hg
manpage of the hgdate
filter:
hgdate Date. Returns the date as a pair of numbers: "1157407993 25200" (Unix timestamp, timezone offset).
(Side note: The timezone offset, a little confusingly, is negated: I'm in UTC+2, but the offset is given as -7200 seconds. However, this is only important if you want the local time. If you're after UTC, you will be ignoring the offset in any case.)
Overall, the date|hgdate
variant only saves a few characters, but personally I find it conceptually cleaner and easier to understand. It may also be a little more robust against potential future bugs in Mercurial, since it involves fewer parsing and formatting operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With