Thirupathi Thangavel
Thirupathi Thangavel

Reputation: 2465

tcl clock scan snmp Date Time format

The standard snmp DateTime format is as below.

http://net-snmp.sourceforge.net/docs/mibs/host.html#DateAndTime

"2016-10-3,2:15:27.0,-4:0"

Now I'm trying to convert this value into epoch using tcl's clock scan

The formatting options in here for scanning does not support fractional seconds and time zone I think.

% clock scan $value2 -format {%Y-%m-%d %H:%M:%S}
input string does not match supplied format

I've managed to split the values into date, time and timeZone.

% set value "2016-10-3,2:15:27.0,-4:0"
2016-10-3,2:15:27.0,-4:0
% set value [split $value ,]
2016-10-3 2:15:27.0 -4:0
% lassign $value date time timeZone
%

How do I proceed after this?

Upvotes: 1

Views: 1679

Answers (2)

Peter Lewerin
Peter Lewerin

Reputation: 13252

You could proceed like this (checking scan results for each step: neither of these is of course the final result):

clock scan $date -format %Y-%N-%e

lassign [split $time .] t d
clock scan $t -format %k:%M:%S

You'll have to decide what to do with the deci-second part (in d).

lassign [split $timeZone :] h m ; # or:
scan $timeZone %d:%d h m
clock scan [format {%+03d%02d} $h $m] -format %z

Exactly what clock field specifiers to use depends on the basic format: adjust as needed. AFAICT these specifiers match the format.

To get the final time value:

clock scan "$date $t [format {%+03d%02d} $h $m]" -format "%Y-%N-%e %k:%M:%S %z"

Documentation: clock, format, lassign, scan, split

Upvotes: 2

Donal Fellows
Donal Fellows

Reputation: 137627

The first part that is a problem is the fractional second. Also, the timezone is not in a form that we can support (there's only so much we can do; we focused on making the parser able to handle common parts of the ISO timestamp format).

However, that does mean we can clean things up fairly easily. There's a few steps to this, and we'll use regexp, scan and format to help:

# Your example, in a variable for my convenience
set instant "2016-10-3,2:15:27.0,-4:0"

# Take apart the problem piece; REs are *great* for string parsing!
regexp {^(.+)\.(\d+),(.+)$} $instant -> timepart fraction timezone

# Fix the timezone format; we use [scan] for semantic parsing...
set timezone [format "%+03d%02d" {*}[scan $timezone "%d:%d"]]

# Parse the time properly now that we can understand all the pieces
set timestamp [clock scan "$timepart $timezone" -format "%Y-%m-%d,%k:%M:%S %z"]

Let's check whether that produces the right sort of output (this is in an interactive session):

% clock format $timestamp
Mon Oct 03 07:15:27 BST 2016

Looks good to me. I suppose you could add the fractional part of the original instant on the end, but then clock format wouldn't like it.

Upvotes: 2

Related Questions