perl mysql (3) perl CGI (3)
Exchange Links About this site Links to us 
|
Convert a date from Apache's string format to mysql's date format in perl
6 comments. Current rating: (4 votes). Leave comments and/ or rate it.
Question: Apache logs dates in this form: [25/Apr/2005:11:45:59 -0400] and I need to insert this string in a mysql table as a datetime value.
How can I convert it?
Answer: mysql has powerful date handling functions, which unfortunately vary from version to version substantially.
You may use the following perl code instead - it converts
25/Apr/2005:11:45:59
to
2005-04-25 11:45:59
 | |  | | %mo = (
'Jan'=>'01',
'Feb'=>'02',
'Mar'=>'03',
'Apr'=>'04',
'May'=>'05',
'Jun'=>'06',
'Jul'=>'07',
'Aug'=>'08',
'Sep'=>'09',
'Oct'=>'10',
'Nov'=>'11',
'Dec'=>'12');
$time = substr($time,7,4) . '-' . $mo{substr($time,3,3)} . '-' . substr($time,0,2) . ' ' . substr($time,12);
| |  | |  |
Comments:
|
anonymous from India
|
 |
|
|
|
|
anonymous from India
|
 |
|
|
very very very very very very bad
|
|
anonymous from India
|
 |
|
|
bad
|
|
anonymous from United States
|
 |
|
|
'very very bad' isn't helpful, tool.
Use mysql's STR_TO_DATE function, like so:
select STR_TO_DATE('11/Jun/2006:06:28:16', '%d/%b/%Y:%k:%i:%s');
To handle the offset, you can do something like this:
select CONVERT_TZ(STR_TO_DATE('11/Jun/2006:06:28:16', '%d/%b/%Y:%k:%i:%s'), 'GMT', '-04:00');
|
|
anonymous from India
|
|
|
|
|
|
anonymous from United States
|
|
|
|
It is much clearer.
|
|