简体   繁体   中英

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:

"Lastname, Firstname account_last_used_date"

I've tried dateutil parser, however it states this list is an invalid string. I need to keep the names and the dates together. I've also tried datetime but i'm having issues with "datetime not defined". I'm very new to Python, so forgive me if i've missed an easy solution.

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. Honestly, any help here is massively welcome!

The CSV format is:

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

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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