【问题标题】:how to convert list of dates into Unix timestamps如何将日期列表转换为 Unix 时间戳
【发布时间】:2022-12-15 13:37:22
【问题描述】:

我有一个日期列表,它的长度是无序的,并且有日、月、年模式。我想返回有序的日期和 utc 格式的日期。

我试过的:

 from datetime import timezone
 import datetime

 data_lst = ['07 17', '01 2017', '05 2015', '2016', '7 04 1988']
 utc = []
 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

我到目前为止所得到的,

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

但我的预期结果:

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

我卡在了第 20 行。

【问题讨论】:

  • 你想把你的日期变成UNIX 时间戳?然后你需要澄清一件事:UNIX 时间戳精确到秒,但是你有一个分辨率一天最好。什么时间您是否应该假设这些日期将它们变成 UNIX 时间戳?午夜?转向是否有意义日期进入UNIX 时间戳?
  • @deceze 是的,我想将日期转换为 UNIX 时间戳。时间可以是随机的,午夜时间也可以。

标签: python datetime utc


【解决方案1】:
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)

这将输出

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

您还需要将“欧洲/伦敦”更改为您的时区 要反转列表,请将排序行更改为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2016-04-24
    • 2012-07-04
    相关资源
    最近更新 更多