How Do You Set a Date-Time Value with a Default Year in Python?

Problem scenario
You are printing out some dates with a Python program. You are using the datetime module and the strptime method. The year is always defaulting to 1900 because the log entries have no year designated in them. How do you seed the dates with a specific year of your choice?

Solution
Here is an example of how to seed the dates with the year 2021 (but it assumes you have a file name auth.log with dates without years in it):

import datetime
from datetime import datetime, timezone
log_reader = open('auth.log', 'r')
for line in log_reader:
    dt_of_log = datetime.strptime('2021 ' + line[:6], '%Y %b %d')
    print(dt_of_log)

Leave a comment

Your email address will not be published. Required fields are marked *