1

I have a code snippet which looks like this:

Logger_time = [
    '6/30/2020 3:15 PM', '6/30/2020 3:16 PM',
    '6/30/2020 3:17 PM', '6/30/2020 3:18 PM',
    '6/30/2020 3:19 PM', '6/30/2020 3:20 PM',
    '6/30/2020 3:21 PM', '6/30/2020 3:22 PM',
    '6/30/2020 3:23 PM', '6/30/2020 3:24 PM',
    '6/30/2020 3:25 PM', '6/30/2020 3:26 PM',
    '6/30/2020 3:27 PM', '6/30/2020 3:28 PM',
    '6/30/2020 3:29 PM', '6/30/2020 3:30 PM',
    '6/30/2020 3:31 PM', '6/30/2020 3:32 PM',
    '6/30/2020 3:33 PM', '6/30/2020 3:34 PM']

newLoggertime = []

for ti in Logger_time:

    timestamp = time.mktime(datetime.strptime(ti, '%m/%d/%Y %I:%M %p'))
    newLoggertime.append(timestamp)

When I run this code I have suddenly started getting this error

TypeError: Tuple or struct_time argument required

I cant seem to find the reason behind this. Basically this code converts date and time in a particular format to timestamp

Kemp
  • 3,467
  • 1
  • 18
  • 27
MNM
  • 13
  • 1
  • 4
  • Does this answer your question? [Convert string date to timestamp in Python](https://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python) – FObersteiner May 12 '21 at 14:02
  • No but I found what the problem was: timestamp = time.mktime(time.strptime(ti, '%m/%d/%Y %I:%M %p')) – MNM May 12 '21 at 14:16
  • ok I admit the answers there do not exactly match your use-case and partly aren't up to date anymore. anyway, I think @Kemp 's answer shows an easier way: just use the timestamp method of the datetime object. – FObersteiner May 12 '21 at 14:21

1 Answers1

1

datetime.strptime returns a datetime object, while time.mktime requires a tuple, as the message states.

Your options are to call timetuple on the datetime object and pass this to time.mktime:

timestamp = time.mktime(datetime.strptime(ti, '%m/%d/%Y %I:%M %p').timetuple())

or call timestamp on the datetime object to get the timestamp directly:

timestamp = datetime.strptime(ti, '%m/%d/%Y %I:%M %p').timestamp()

Though be aware of the notes related to timestamp.

Kemp
  • 3,467
  • 1
  • 18
  • 27
  • Right. If I use time instead of datetime it works as well. timestamp = time.mktime(time.strptime(ti, '%m/%d/%Y %I:%M %p')) – MNM May 12 '21 at 14:44