Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting non-iso8601 datetime strings to epoch (mktime) format #3047

Open
luckman212 opened this issue Feb 19, 2024 · 4 comments
Open

Converting non-iso8601 datetime strings to epoch (mktime) format #3047

luckman212 opened this issue Feb 19, 2024 · 4 comments
Labels

Comments

@luckman212
Copy link

Version

jq-1.7.1

Problem

I am working with an API that outputs dates in this format:

{
  "lastSeen": "2024-02-19T17:37:01-05:00",
  "lastConnectionDurationS": 190.612964
}

I'm trying to parse that lastSeen string into epoch time, something like

$ jq '.lastSeen | strptime("%Y-%m-%dT%H:%M:%S-05:00") | mktime'
1708364221

I am looking for a more generalized function that can accept a date formatted in this way and turn it into the correct epoch time integer. My jq-fu isn't up to the challenge. Was wondering if anyone had ideas. I've read the related links below.

Related

@nicowilliams
Copy link
Contributor

fromdate would do it if only your datetime strings had a "Z" at the end, so you could (.lastSeen + "Z")|fromdate.

@luckman212
Copy link
Author

Thanks, but because of the -05:00, I get this:

$ echo '{ "lastSeen": "2024-02-19T17:37:01-05:00" }' | jq '.lastSeen + "Z" | fromdate'
jq: error (at <stdin>:1): date "2024-02-19T17:37:01-05:00Z" does not match format "%Y-%m-%dT%H:%M:%SZ"

@nicowilliams
Copy link
Contributor

Oh, sorry, I went too quick and missed the time zone offset.

You can use the %z format specifier:

$ jq -n '"2024-02-19T17:37:01-05:00" | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime'
1708364221

However, %z requires that the : not be present in the time zone offset, so you might have to remove it:

$ jq -n '("2024-02-19T17:37:01"|length) as $n | "2024-02-19T17:37:01-05:00" as $t | ($t[0:$n] + $t[$n:$n+3] + $t[$n+4:$n+6]) | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime'
1708364221

@luckman212
Copy link
Author

Thank you. That works! Here are some other variants that seem to work also

$ jq -n '"2024-02-19T17:37:01-05:00" as $o | $o[-6:] as $tz | $tz|sub(":";"") as $ntz | $o|sub($tz;$ntz) | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime'
1708364221
$ jq -n '"2024-02-19T17:37:01-05:00" | gsub(":(?=[0-9]{2}$)";"") | strptime("%Y-%m-%dT%H:%M:%S%z") | mktime'
1708364221

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants