On 6/1/2012 12:44 PM, Kenny McCormack wrote:
> In article<
95a2b2e6-8554-4e81...@googlegroups.com>,
> Bryan<
bryan...@gmail.com> wrote:
>> On Thursday, May 31, 2012 11:09:51 PM UTC-4, Ed Morton wrote:
>>> Try this:
>>>
>>> ... strftime(format_B,mktime(date_2))
>>
>> this is a great idea, thanks. I can see how that works,..
>>
>> ... soooo... sorry, this isn't sinking in yet - is there a time function
>> that will take an argument in format %d%m%y ? i.e. mktime takes YYYY MM
>> DD HH MM SS [DST], strftime takes a number of secs since the epoch, so -
>> without changing dates by hand into YYYY MM DD HH MM SS [DST] I do not
>> see how to go from %d%m%y to anything else. (I have a script with dates
>> already hand-written in this format, e.g. some_event="01Jan10";
>
> The general idea is that GAWK only has the one function for making "epoch
> time numbers" - and that is mktime(). So, you usually have to write the
> code yourself to convert whatever time format you have into the format that
> mktime() wants. In particular, you will almost certainly have to write code
> to lookup the month names. And, yes, this has been done a thousand times,
> by a thousand different programmers - seems a shame that it has to be
> re-rolled each time.
>
> On a more general note, I think what you're looking for is strptime(), which
> is generally described as being the "inverse of strftime()". Unfortunately,
> there doesn't exist any (direct, user-accessible) interface to it in GAWK.
Even strptime() couldn't handle the OPs time format though as it requires
non-alphanumeric characters between time specifiers.
> I've often thought about cobbling something together to give access to
> strptime(). I'd like to do it with my "call_any()" interface - not sure if
> this will work or not, though. It could certainly be done, of course, using
> an extension library.
That got me wondering how hard it'd be to write a simple, stripped down
strptime() that'd work for most applications. Here's what I came up with FWIW:
$ cat strptime.awk
function strptime(val, fmt, fmtA,valA,i,n,specA,spec)
{
n = split(val,valA,/[^[:alnum:]]+/)
split(fmt,fmtA,/[^[:alpha:]]+/)
for (i=1; i<=n; i++) {
specA[fmtA[i+1]] = valA[i]
}
if (!specA["m"]) {
match("janfebmaraprmayjunjulaugsepoctnovdec",tolower(specA["b"]))
specA["m"] = (RSTART+2)/3
}
spec = sprintf("%4d %2d %2d %2d %2d %2d",\
specA["Y"], specA["m"], specA["d"], specA["H"], specA["M"], specA["S"])
return mktime(spec)
}
BEGIN{ FS="\t" }
{ print $1 " -> " strftime( "%D (%T)", strptime($1,$2) ) }
$ cat file
6 Dec 2001 12:33:45 %d %b %Y %H:%M:%S
6 dec 2001 %d %b %Y
06 12 2001 %d %m %Y
$ awk -f strptime.awk file
6 Dec 2001 12:33:45 -> 12/06/01 (12:33:45)
6 dec 2001 -> 12/06/01 (00:00:00)
06 12 2001 -> 12/06/01 (00:00:00)
All it supports is %d, %b, %m, %Y, %H, %M, and %S specifiers. I do agree a
builtin strptime() would be a great addition to gawks time functions.
Regards,
Ed.