Files
Python_Examples/datetime.py
sa6kad d68d0033ee datetime.py
Added datetime example
2024-12-17 00:29:31 +01:00

32 lines
1.0 KiB
Python

from datetime import datetime, timedelta
from dotenv import set_key, load_dotenv
import os
# Current time
datetime.now() # Returns: 2024-12-16 23:09:13.906199
# Current time with a defined format, here without milliseconds
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Create a timedelta object, can use to compare with a timestamp
timedelta(minutes=50) # Returns: 0:50:00
# Read timestamp from a .env, last argument defines the timestamp format in the file
TOKEN_TIME = datetime.strptime(os.getenv("TOKEN_TIME"), "%Y-%m-%d %H:%M:%S")
# Timestamp comparison example:
MAX_AGE = timedelta(minutes=50)
TIMESTAMP = datetime.strptime('2024-12-16 23:09:13', "%Y-%m-%d %H:%M:%S")
print(TIMESTAMP < datetime.now() - MAX_AGE)
# Output:
# False if TIMESTAMP is NOT older than 50 minutes. I.e. if timestamp time is less than/not older then current-time minus timedelta
# True if older
print(TIMESTAMP > datetime.now() - MAX_AGE)
# Output:
# True if time in the TIMESTAMP is more than (older) the current tome minus timedelta