autohotkeyunix-timestamp

Ahk v2 current Unix Timestamp


I'm trying to get the current timestamp, which is the number of seconds past from 01/01/1970. But it seems like there isn't a function like that in ahk like some languages do. I tried to do research but it doesn't seem like there's a way to do it other than just multiplying and summing up years, months, hours, minutes and seconds.

So my question is how do we, mimick this function in ahk? (I won't provide a code sample because it's irrelevant here.)


Solution

  • While AutoHotkey lacks any builtin function for this, you can implement it yourself with DateDiff.

    A naive implementation may look like this:

    epoch := "19700101000000"
    diff := DateDiff(A_Now, epoch, "Seconds")
    MsgBox(diff)
    

    However, it's important to be aware that AutoHotkey's DateDiff uses local time and does not accept any timezone information in any circumstance. So if this distinction is important to your use case, you need to account for the local time offset. That may look something like this:

    epoch := "19700101000000"
    local_diff := DateDiff(A_Now, epoch, "Seconds")
    utc_offset_seconds := DateDiff(A_Now, A_NowUTC, "Seconds")
    unix_timestamp := local_diff - utc_offset_seconds
    MsgBox(unix_timestamp)
    

    In my limited testing, this provides the unix timestamp rounded down to the nearest second and produces the same result as Python's time.time:

    comparison with Python

    It's also worth noting the best resolution you can get in DateDiff is seconds.