Translating a Timestamp

A timestamp is one of those tricky chunks of data that’s not really a single value. Often it’s a clutch of integers or — worse — it’s a string. To do time calculations on the timestamp, you must translate it into a more useful form.

Recently, I worked on a project where the timestamp is presented as a two string values:

2018_05_15 12:18:22

Following those two fields were other data tidbits, presented as thousands of rows of values. Because the timestamps aren’t recorded at regular intervals, I translated them into time_t (epoch) values. It was a fun exercise for me, so I thought I’d share it with you as this month’s Exercise, but not the entire thing.

Your job is easier than mine because I’m not requiring that you create a time_t value. Instead, extract the year, month, day, hour, minute, and second values from the timestamp string shown above. Place those values into a datetime structure:

struct datetime {
    int year;
    int month;
    int day;
    int hour;
    int minute;
    int second;
};

If you like, you can go further and translate those integer values into a time_t value. Directions for doing so are found in this post, but for this month’s Exercise the goal is simply to extract values from the given string.

It’s okay to assume that the string remains constant: Every row in the dataset uses the same string format. You can safely assume that the values are always found at the same locations within the string. Or your solution can be more flexible, though it doesn’t need to be.

Here’s a sample run of my solution:

Time stamp string is '2018_05_15 12:18:22'
Timestamp structure is 2018 5 15 12 18 22

Please try this puzzle on your own before you view my solution.

Leave a Reply