Home > Software design >  Convert dictionary timestamp key-value pairs into datetime
Convert dictionary timestamp key-value pairs into datetime

Time:10-09

I have a dictionary which has a timestamp stored as key and value pairs:

timestamp_info = {
    'day': 8, 'fold': 0, 'hour': 0,
    'max': {'day': 31, 'fold': 0,'hour': 23},
    'microsecond': 639000, 'minute': 17, 'month': 10, 'second': 35, 'year': 2021
}

I am trying to take timestamp from dictionary and convert to datetime.datetime timestamp format. I tried the following but it does not work as it asks for str (exact error is: "strptime() argument 1 must be str, not dict"):

result = datetime.datetime.strptime(timestamp_info, "%Y-%m-%d %H:%M:%S")

I want this result to be compared with datetime.datetime.now and take difference in seconds between current timestamp and result, that is the reason I need timestamp format.

CodePudding user response:

Chirs Oram already shows how to build a string that you can then parse with strptime(). Alternatively, you can pass the values directly to datetime():

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

year = timestamp_info['year']
month = timestamp_info['month']
day = timestamp_info['day']
hour = timestamp_info['hour']
minute = timestamp_info['minute']
second = timestamp_info['second']

result = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)

Or you can do this more succinctly by removing the attributes not needed for datetime:

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

del timestamp_info['fold']
del timestamp_info['max']

result = datetime.datetime(**timestamp_info)

CodePudding user response:

You can extract each part of the timestamp in the specified format, and concatenate them into a string:

timestamp_info = {
    'day':8, 'fold':0,'hour':0, 'max':{'day':31, 'fold':0,'hour':23},
    'microsecond':639000,'minute':17,'month':10,'second':35, 'year':2021
}

year = str(timestamp_info['year'])
month = str(timestamp_info['month'])
day = str(timestamp_info['day'])
hour = str(timestamp_info['hour'])
minute = str(timestamp_info['minute'])
second = str(timestamp_info['second'])
timestamp = '-'.join([year, month, day])   ' '   ':'.join([hour, minute, second])

result = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")

Which results in:

2021-10-08 00:17:35
  • Related