2024-02-26 13:28:32 +05:30
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
|
|
|
|
|
# Format date
|
|
|
|
|
def format_date_to_string(date, format='%d %b, %Y'):
|
|
|
|
|
return date.strftime(format)
|
|
|
|
|
|
|
|
|
|
# Format date or time
|
|
|
|
|
def format_datetime_to_sting(dt, format='%d %b, %Y %H:%M:%S'):
|
|
|
|
|
return dt.strftime(format)
|
|
|
|
|
|
|
|
|
|
# Get current date
|
|
|
|
|
def get_current_date():
|
|
|
|
|
return datetime.now()
|
|
|
|
|
|
|
|
|
|
# Get current time
|
|
|
|
|
def get_current_time():
|
|
|
|
|
return datetime.now().time()
|
|
|
|
|
|
2024-03-11 14:48:48 +05:30
|
|
|
def get_date_range(days):
|
|
|
|
|
end_date = datetime.now()
|
|
|
|
|
start_date = end_date - timedelta(days=int(days))
|
|
|
|
|
return start_date, end_date
|
|
|
|
|
|
2024-02-26 13:28:32 +05:30
|
|
|
# Get current date in a specific timezone
|
|
|
|
|
from pytz import timezone
|
|
|
|
|
def get_current_date_in_timezone(timezone_str='UTC'):
|
|
|
|
|
tz = timezone(timezone_str)
|
|
|
|
|
return datetime.now(tz)
|
|
|
|
|
|
|
|
|
|
# Convert string to datetime
|
|
|
|
|
def string_to_date(date_string, format='%Y-%m-%d'):
|
|
|
|
|
return datetime.strptime(date_string, format)
|
|
|
|
|
|
|
|
|
|
# Convert string to datetime
|
|
|
|
|
def string_to_datetime(datetime_string, format='%Y-%m-%d %H:%M:%S'):
|
|
|
|
|
return datetime.strptime(datetime_string, format)
|
|
|
|
|
|
|
|
|
|
# Get difference between two dates
|
|
|
|
|
def get_date_difference(date1, date2):
|
|
|
|
|
return abs(date2 - date1)
|
|
|
|
|
|
|
|
|
|
# Get difference between two datetimes
|
|
|
|
|
def get_datetime_difference(datetime1, datetime2):
|
|
|
|
|
return abs(datetime2 - datetime1)
|
|
|
|
|
|
|
|
|
|
# Add days to a given date
|
|
|
|
|
def add_days_to_date(date, days):
|
|
|
|
|
return date + timedelta(days=days)
|
|
|
|
|
|
|
|
|
|
# Subtract days from a given date
|
|
|
|
|
def subtract_days_from_date(date, days):
|
|
|
|
|
return date - timedelta(days=days)
|
|
|
|
|
|
|
|
|
|
# Check if a year is a leap year
|
|
|
|
|
def is_leap_year(year):
|
|
|
|
|
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
|
|
|
|
|
|
|
|
|
|
# Get the last day of a given month and year
|
|
|
|
|
def last_day_of_month(year, month):
|
|
|
|
|
if month == 12:
|
|
|
|
|
year += 1
|
|
|
|
|
month = 1
|
|
|
|
|
else:
|
|
|
|
|
month += 1
|
|
|
|
|
return datetime(year, month, 1) - timedelta(days=1)
|
|
|
|
|
|
|
|
|
|
# Check if a date is within a specific range
|
|
|
|
|
def is_date_within_range(date, start_date, end_date):
|
|
|
|
|
return start_date <= date <= end_date
|