Defining the convert_unix_seconds() method

The Unix timestamp is the most straightforward of the three timestamps that we'll convert in this chapter. On lines 175 through 179, we define the method and its docstrings before stepping into an if statement. The if statement on line 180 evaluates whether the value of the radio button described earlier is equal to the raw string or formatted. If it's set to raw, we'll parse the timestamp as a count of seconds since 1970-01-01 00:00:00.0000000. This is relatively simple because this is the epoch used by the datetime.datetime.fromtimestamp() method. In this case, we only have to convert the input into a float as seen on lines 182 and 183 before conversion.

Afterward, on lines 183 and 184, we format the newly formed datetime object as a string in the YYYY-MM-DD HH:MM:SS format. The logic on line 182 is wrapped in a try-except statement to catch any bugs and report them to the log file and to the user interface in a simplified form. This allows us to test each formula when a date is entered. Line 188 outlines that the conversion error will be displayed when we are unsuccessful in converting the timestamp. This will alert the user that there was an error and allow them to determine whether it's anticipated or not:

175     def convert_unix_seconds(self):
176 """
177 The convert_unix_seconds method handles the conversion of
178 timestamps per the Unix seconds format
179 """
180 if self.time_type.get() == 'raw':
181 try:
182 dt_val = datetime.datetime.fromtimestamp(
183 float(self.input_time.get())).strftime(
184 '%Y-%m-%d %H:%M:%S')
185 self.processed_unix_seconds = dt_val
186 except Exception as e:
187 logger.error(str(type(e)) + "," + str(e))
188 self.processed_unix_seconds = str(
189 type(e).__name__)

If the timestamp is a formatted value, we need to first parse the input before attempting to convert it into a Unix timestamp, as it may not follow the intended format. Once converted by dateutil.parser, we can use the predefined epoch object to calculate the delta in seconds between the timestamp and epoch on lines 195 through 197. If an error occurs, it will be caught as in the prior if statement, logged, and displayed to the user, as follows:

191         elif self.time_type.get() == 'formatted':
192 try:
193 converted_time = duparser.parse(
194 self.input_time.get())
195 self.processed_unix_seconds = str(
196 (converted_time - self.epoch_1970
197 ).total_seconds())
198 except Exception as e:
199 logger.error(str(type(e)) + "," + str(e))
200 self.processed_unix_seconds = str(
201 type(e).__name__)