Cat Feeder  1.0.0
The Cat feeder project
Loading...
Searching...
No Matches
sql_time_manipulation.py
Go to the documentation of this file.
1r"""
2# +==== BEGIN CatFeeder =================+
3# LOGO:
4# ..............(..../\
5# ...............)..(.')
6# ..............(../..)
7# ...............\‍(__)|
8# Inspired by Joan Stark
9# source https://www.asciiart.eu/
10# animals/cats
11# /STOP
12# PROJECT: CatFeeder
13# FILE: sql_time_manipulation.py
14# CREATION DATE: 11-10-2025
15# LAST Modified: 14:52:46 19-12-2025
16# DESCRIPTION:
17# This is the backend server in charge of making the actual website work.
18# /STOP
19# COPYRIGHT: (c) Cat Feeder
20# PURPOSE: File in charge of containing the functions that allow for time conversion between datetime and strings.
21# // AR
22# +==== END CatFeeder =================+
23"""
24
25
26from datetime import datetime
27
28from display_tty import Disp, initialise_logger
29
30from . import sql_constants as SCONST
31
32
34 """Handle time conversion between datetime objects and strings.
35
36 This class provides methods to convert datetime objects to strings and
37 vice versa, with support for SQL-compatible formats.
38
39 Attributes:
40 debug (bool): Debug mode flag.
41 date_only (str): Format string for date-only conversion.
42 date_and_time (str): Format string for date and time conversion.
43 disp (Disp): Logger instance for debugging and error reporting.
44 """
45
46 disp: Disp = initialise_logger(__qualname__, False)
47
48 def __init__(self, debug: bool = False) -> None:
49 """Initialize the SQLTimeManipulation instance.
50
51 Args:
52 debug (bool, optional): Enable debug logging. Defaults to False.
53 """
54 # ------------------------ The logging function ------------------------
55 self.disp.update_disp_debug(debug)
56 self.disp.log_debug("Initialising...")
57 # -------------------------- Inherited values --------------------------
58 self.debug: bool = debug
59 # ----------------------- Inherited from SCONST -----------------------
60 self.date_only: str = SCONST.DATE_ONLY
61 self.date_and_time: str = SCONST.DATE_AND_TIME
62 self.disp.log_debug("Initialised")
63
64 def datetime_to_string(self, datetime_instance: datetime, date_only: bool = False, sql_mode: bool = False) -> str:
65 """Convert a datetime object to a formatted string.
66
67 Args:
68 datetime_instance (datetime): Datetime to format.
69 date_only (bool, optional): Return only the date portion. Defaults to False.
70 sql_mode (bool, optional): Include millisecond precision for SQL. Defaults to False.
71
72 Raises:
73 ValueError: If the input is not a datetime instance.
74
75 Returns:
76 str: Formatted datetime string.
77 """
78 if not isinstance(datetime_instance, datetime):
79 self.disp.log_error(
80 "The input is not a datetime instance.",
81 "datetime_to_string"
82 )
83 raise ValueError("Error: Expected a datetime instance.")
84 if date_only:
85 return datetime_instance.strftime(self.date_only)
86 converted_time = datetime_instance.strftime(self.date_and_time)
87 if sql_mode:
88 microsecond = datetime_instance.strftime("%f")[:3]
89 return f"{converted_time}.{microsecond}"
90 return converted_time
91
92 def string_to_datetime(self, datetime_string_instance: str, date_only: bool = False) -> datetime:
93 """Convert a formatted string to a datetime object.
94
95 Args:
96 datetime_string_instance (str): Formatted datetime string.
97 date_only (bool, optional): Parse using the date-only format. Defaults to False.
98
99 Raises:
100 ValueError: If the input is not a string instance.
101
102 Returns:
103 datetime: Parsed datetime object.
104 """
105 if not isinstance(datetime_string_instance, str):
106 self.disp.log_error(
107 "The input is not a string instance.",
108 "string_to_datetime"
109 )
110 raise ValueError("Error: Expected a string instance.")
111 if date_only:
112 return datetime.strptime(datetime_string_instance, self.date_only)
113 return datetime.strptime(datetime_string_instance, self.date_and_time)
114
115 def get_correct_now_value(self) -> str:
116 """Get the current date and time in the correct format for the database.
117
118 Returns:
119 str: Formatted current date and time.
120 """
121 current_time = datetime.now()
122 return current_time.strftime(self.date_and_time)
123
125 """Get the current date in the correct format for the database.
126
127 Returns:
128 str: Formatted current date.
129 """
130 current_time = datetime.now()
131 return current_time.strftime(self.date_only)
str datetime_to_string(self, datetime datetime_instance, bool date_only=False, bool sql_mode=False)
datetime string_to_datetime(self, str datetime_string_instance, bool date_only=False)