Search code examples
pythondatetimeunix-timestamp

how to convert list of dates into Unix timestamps


I have a list of dates that has unordered length and with day,mon,year pattern.and i want to return both ordered date and Unix timestamps.

what i have tried:

 from datetime import timezone
 import datetime

 data_lst = ['07 17', '01 2017', '05 2015', '2016', '7 04 1988']
 unix = []
 standard_date = []
 for i in data_lst:
    if i:
        data = i.split()
        if len(data) == 3:
            date = f'{data[0]}/{data[1]}/{data[2]}'
        if len(data) == 2:
            date = f'01/{data[0]}/{data[1]}'
        if len(data) == 1:
            date = f'01/01/{data[0]}'
        standard_date.append(date)
        d_m_y = date.split('/')
        if len(d_m_y[2]) == 2:
            d_m_y[2] = '20' + d_m_y[2]
        date = datetime.datetime  # i stuck here

what i got so far,

 print(standard_date)
 >>> ['01/07/17', '01/01/2017', '01/05/2015', '01/01/2016', '7/04/1988']
 

but my expected result:

 print(standard_date)
 print(unix)
 >>> ['01/07/17', '01/01/2017', '01/05/2015', '01/01/2016', '7/04/1988']
 >>> ['1498867....', '148322...', 'unix timestamp(01/05/2015)',and so on]

i got stuck in line 20.


Solution

  • from datetime import datetime
    import pytz
    dates = ['07 17', '01 2017', '05 2015', '2016', '7 04 1988']
    unix_list = []
    def try_parsing_date(text):
        for fmt in ('%m %y', '%m %Y', '%Y', '%y', '%d %m %y', '%d %m %Y'):
            try:
                return datetime.strptime(text, fmt)
            except ValueError:
                pass
        raise ValueError('no valid date format found')
    
    
    for date in dates:
        date = try_parsing_date(date)
        london_tz = pytz.timezone('Europe/London')
        date = london_tz.localize(date)
        utc_dt = date.astimezone(tz=pytz.utc)
        date_unix_tuple_list.append((date.strftime("%d/%m/%y"), int(utc_dt.timestamp())))
        date_unix_tuple_list.sort(key=lambda x: x[1]) # this line sorts the dates 
    standard_date = list(map(lambda x: x[0], date_unix_tuple_list))
    utc = list(map(lambda x: x[1], date_unix_tuple_list))
    print(standard_date)
    print(utc)
    

    This will output

    ['07/04/88', '01/05/15', '01/01/16', '01/01/17', '01/07/17']
    [576374460, 1430438460, 1451606460, 1483228860, 1498867260]
    

    You will also need to change 'Europe/London' to your timezone To reverse the list, change the sorting line to

      date_unix_tuple_list.sort(key=lambda x: x[1], reverse=True)