将日期从可读字符串转换为更标准的 - python

我的日期格式为Fri 27th Aug,这肯定是您梦imagine以求的编程方式的噩梦。

我想知道如何最好地将它们转换为美国日期格式08/27/13。我需要指定月份中的年份,即8月-12月表示13,而1月-7月表示14

我正在考虑查找如何在正则表达式中执行此操作,甚至只是进行一系列字符串替换。

但复杂的是,我有一个字符串列表,并非所有字符串都是这种形式的日期。如果其他人的数字里面有数字,我该如何测试此表格的日期,然后替换呢?

例如

list = ['not a date', 'als0 not a dat3', 'Wed 5th Jan', ... , 'no date here']

测试的要求使regex看起来很合适,但是我相对于在Python中使用re读了很多SO文章,尽管我不知道为什么。我是否应该(学会使用)并使用它?

有了@Allan的回答,我已经可以解决以下问题:

def is_date(string):
    tmp = string.replace('th','')
    string = tmp.replace('rd','')
    tmp = string.replace('nd','')
    string = tmp.replace('st','')
    try:
        d = strptime(string, "%a %d %b")
        date = str(d[1]) + "/" + str(d[2]) + "/"
        if d[1] >= 8:
            date += "13"
        else:
            date += "14"
        return date
    except ValueError:
        return 0

感谢您的回答,@ Allan,@ adsmith和@codnodder。

python参考方案

Dateutil.parser将为您做更多的事情:

http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

将字符串分配给numpy.zeros数组[重复] - python

This question already has answers here: Weird behaviour initializing a numpy array of string data                                                                    (4个答案)         …