Just a few general things to start with,
- You would do better to parse XML with something from cpan's XML offerings.
- Your sql would benefit from placeholders.
- Your time-of-day handling could be cut to nothing with &POSIX::strftime.
- Try doing this with taint mode on. Some checking of results might be wise.