Search code examples
linuxunixawk

awk: try to convert timestamp string to unix epoch time


I try to convert a timestamp string to unix epoch time using awk but fail after several attempts.

$ echo "2024-04-16 16:32:38.108580" | awk '{ epoch = mktime(gensub(/[:-]/, " ", "g", $1)) + substr($1, index($1, ".")+1) ; print epoch }'
2023

Solution

  • mktime() is looking for input of the format YYYY MM DD HH MM SS so in this case we want to:

    ### convert this:
    
    2024-04-16 16:32:38.108580
    
    ### to this:
    
    2024 04 16 16 32 38
    

    We can do this a couple ways:

    gensub(/[:-]|[.].*$/, " ", "g")
      gsub(/[:-]|[.].*$/, " ")
    

    Since I don't designate a field or variable to operate on the functions operate on the entire line (ie, $0).

    OP's code only performs operations on the first white space delimited field ($1) which in this case is 2024-04-16. OP will either need to designate the first 2 fields ($1 " " $2) or the whole line ($0 - default behavior if no field designated).

    Since the sample input only has the 2 white space delimited fields we'll stick with processing the entire line ($0).

    Pulling these changes into a new awk script:

    ### convert input to mktime() format:
    
    $ echo "2024-04-16 16:32:38.108580" | awk '{ print gensub(/[:-]|[.].*$/, " ", "g") }'
    2024 04 16 16 32 38
    
    ### convert to epoch seconds:
    
    $ echo "2024-04-16 16:32:38.108580" | awk '{ print mktime(gensub(/[:-]|[.].*$/, " ", "g")) }'
    1713303158
    
    ### reverse operation to verify we've got the correct epoch seconds
    
    $ date '+%Y-%m-%d %H:%M:%S' -d @1713303158
    2024-04-16 16:32:38
    

    If we need to append the .108580 on the end we can re-use OP's substr( index() ) code as long as we remember to operate on the entire line ($0):

    $ echo "2024-04-16 16:32:38.108580" | awk '{ print mktime(gensub(/[:-]|[.].*$/, " ", "g")) substr($0, index($0, ".")) }'
    1713303158.108580