Domanda

I am trying to convert a date/time of the following format YYYYDDMMHHmm to seconds since epoch in Tcl.

I've tried to do this with the following, but it isn't working:

clock scan 201403251850 -format %Y%m%d%H%M

For the above, I am trying to convert 6:50PM on March 25th, 2014 to seconds since epoc.

How can I achieve this?

Chris

È stato utile?

Soluzione

I tested this on Tcl 8.3.3, so should work with 8.0: The regex may need some tweaking to suit the pre-8.1 regexp engine.

proc scan_datetime {datetime} {
    # expect a datetime string like "6:50PM on March 25th, 2014"
    regexp {^([0-9]+):([0-9]{2})([AP]M) on ([[:alpha:]]+) ([0-9]{1,2}).., ([0-9]{4})} $datetime -> hr min ampm mon day year
    if {$ampm == "PM"} then {incr hr 12} elseif {$hr == 12} then {set hr 0}
    clock scan "$day $mon $year $hr:$min"
}
puts [clock format [scan_datetime "6:50PM on March 25th, 2014"]]
puts [clock format [scan_datetime "12:34AM on February 1st, 2012"]]
Tue Mar 25 18:50:00 EDT 2014
Wed Feb 01 00:34:00 EST 2012

If the above regular expression doesn't work in 8.0, try this:

proc scan_datetime {datetime} {
    set d {[0-9]}
    set a {[A-Za-z]}
    regexp "^($d$d?):($d$d)(\[AP]M) on ($a+) ($d$d?).., ($d$d$d$d)" $datetime -> hr min ampm mon day year
    if {$ampm == "PM"} then {incr hr 12} elseif {$hr == 12} then {set hr 0}
    clock scan "$day $mon $year $hr:$min"
}

Specifically for the format YYYYmmddHHMM:

tcl8.3.3 % set t 201403251452
201403251452
tcl8.3.3 % set d {[0-9]}
[0-9]
tcl8.3.3 % regsub "($d$d$d$d)($d$d)($d$d)($d$d)($d$d)" $t {\2/\3/\1 \4:\5} tt
1
tcl8.3.3 % clock scan $tt
1395773520
tcl8.3.3 % clock format [clock scan $tt]
Tue Mar 25 14:52:00 EDT 2014
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top