简体   繁体   English

如何检查字符串中的日期是否大于给定日期? Python 3

[英]How to check if a date in a string is greater than a given date? Python 3

So I have a CSV file of users which is in the format: 所以我有一个用户CSV文件,格式为:

"Lastname, Firstname account_last_used_date"

I've tried dateutil parser, however it states this list is an invalid string. 我已经尝试过dateutil解析器,但是它指出此列表是无效的字符串。 I need to keep the names and the dates together. 我需要把名字和日期放在一起。 I've also tried datetime but i'm having issues with "datetime not defined". 我也尝试过datetime,但是我遇到了“ datetime not defined”的问题。 I'm very new to Python, so forgive me if i've missed an easy solution. 我对Python还是很陌生,所以如果我错过了一个简单的解决方案,请原谅我。

import re
from datetime import date

with open("5cUserReport.csv","r") as dilly:
    li = [(x.replace("\n","")) for x in dilly]
    li2 = [(x.replace(",","")) for x in li]

    for x in li2:
        match = re.search(r"\d{2}-\d{2}-\d{4}", x)
        date = datetime.strptime(match.group(), "%d-%m-%Y").x()
        print(date)

The end goal is I need to check if the date the user last logged in is longer than 4 months. 最终目标是我需要检查用户上次登录的日期是否超过4个月。 Honestly, any help here is massively welcome! 老实说,我们非常欢迎您的任何帮助!

The CSV format is: CSV格式为:

am_testuser1 02/12/2017 08:42:48
am_testuser11 13/10/2017 17:44:16
am_testuser20 27/10/2017 16:31:07
am_testuser5 23/08/2017 09:42:41
am_testuser50 21/10/2017 15:38:12

Edit: Edited the answer based on the given csv 编辑:根据给定的csv编辑答案

You could do something like this with pandas 你可以用熊猫做这样的事情

import pandas as pd

colnames = ['Lastname,   Firstname', 'Date', 'Time']
df = pd.read_csv('5cUserReport.csv', delim_whitespace=True, skiprows=1, names=colnames, parse_dates={'account_last_used_date': [1,2]}, dayfirst =True)

more_than_4_months_ago = df[df['account_last_used_date'] < (pd.to_datetime('now') - pd.DateOffset(months=4))]
print(more_than_4_months_ago)

The DataFrame more_than_4_months_ago will give you a subset of all records, based on if the account_last_used_date is more than 4 months ago. 数据框more_than_4_months_ago将根据account_last_used_date是否大于4个月前为您提供所有记录的子集。

This is based on the given format. 这基于给定的格式。 Allthough I doubt that this is your actual format, since the given usernames don't really match the format 'firstname, lastname' 尽管我怀疑这是您的实际格式,因为给定的用户名与“名字,姓氏”格式不完全匹配

Lastname, Firstname account_last_used_date
am_testuser1 02/12/2017 08:42:48
am_testuser11 13/10/2018 17:44:16
am_testuser20 27/10/2017 16:31:07
am_testuser5 23/08/2018 09:42:41
am_testuser50 21/10/2017 15:38:12

(I edited 2 lines to 2018, so that the test actually shows that it works). (我编辑了2行到2018年,以便测试实际上表明它有效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM