Logan Lee
Logan Lee

Reputation: 997

Jq strftime() to show time in a specific time zone

How to use jq to convert seconds since Unix epoch to a time string in human readable format but adjusted to Sydney, Australia time zone?

I tried filter:

now | strftime("%Y-%m-%dT%H:%M:%SZ")

But I don't know how to adjust the time format string to convey Sydney, Australia time zone.

Possibly I need to replace "Z" with the relevant time zone?

Upvotes: 2

Views: 5802

Answers (2)

ikegami
ikegami

Reputation: 386406

Both of the following convert to the time zone indicated by the TZ environment variable var:

localtime | strftime(...)
strflocaltime(...)

For example,

$ jq -nr 'now | strftime("%FT%T")'
2022-02-14T06:14:07

$ jq -nr 'now | gmtime | strftime("%FT%T")'
2022-02-14T06:14:07

$ jq -nr 'now | localtime | strftime("%FT%T")'
2022-02-14T02:14:07

$ jq -nr 'now | strflocaltime("%FT%T")'
2022-02-14T02:14:07

That uses your local time, as determined by TZ environment variable. Adjust as needed.

$ TZ=America/Halifax jq -nr 'now | strflocaltime("%FT%T")'
2022-02-14T02:14:07

$ TZ=America/Toronto jq -nr 'now | strflocaltime("%FT%T")'
2022-02-14T01:14:07

$ TZ=America/Vancouver jq -nr 'now | strflocaltime("%FT%T")'
2022-02-14T22:14:07

If you want to convert to different time zones in a single run of jq, you're out of luck. jq doesn't support converting to/from time zones other than UTC and this time zone.

Tested with both 1.5 and 1.6.

Upvotes: 5

pmf
pmf

Reputation: 36296

If you are using jq v1.6, use strflocaltime instead of strftime which displays the time in your timezone.

jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'

Demo

From the manual:

The strftime(fmt) builtin formats a time (GMT) with the given format. The strflocaltime does the same, but using the local timezone setting.

If your timezone is different, set the shell's TZ variable accordingly before calling jq

TZ=Australia/Sydney jq -n 'now | strflocaltime("%Y-%m-%dT%H:%M:%S")'

Upvotes: 0

Related Questions