from datetime import datetime
def sqlite_dt_to_custom_dt(date: str, format: str):
'''
date: input date
format: custom output format\n
Converts string object to datetime object, and extract the date and/or time with custom format.
'''
return datetime.strptime(date, r'%a, %d %b %Y %H:%M:%S %z (%Z)').strftime(format)
# SQLite tuple
t = ('Thu, 9 Jun 2022 12:55:10 +0000 (UTC)',)
# Printing the result
print(sqlite_dt_to_custom_dt(t[0], r'%Y-%m-%d'))
I have to agree with @vbrozik , and you can use his suggestion like this:
from datetime import datetime
from email import utils
def sqlite_dt_to_custom_dt(date: str, format: str):
'''
date: input date
format: custom output format\n
Converts string object to datetime object, and extract the date and/or time with custom format.
'''
return datetime(*utils.parsedate(date)[:-2]).strftime(format)
# SQLite tuple
t = ('Thu, 9 Jun 2022 12:55:10 +0000 (UTC)',)
# Printing the result
print(sqlite_dt_to_custom_dt(t[0], r'%Y-%m-%d'))
And then you can register a converter function using sqlite3.register_converter() and use column names in your query to automatically convert these strings to datetime objects when you fetch your result rows.