Using Ptyhon's time and datetime Modules for Date-Time Operations
import time
import datetime
# Section 1: Time Module Examples ##########
# Example 1: Current Timestamp
print(time.time())
# Example 2: Formatted Date String
print(time.strftime('%Y-%m-%d %H:%M:%S %A'))
print(time.strftime('%Y-%m-%d %X %A'))
print(time.strftime('%Y-%m-%d %X'))
print(time.strftime('%x %X %A'))
print(time.strftime('%Y'))
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# Example 3: Structured Time Object
result = time.localtime()
print(result)
print(result.tm_year)
print(result.tm_mon)
# Section 2: Datetime Module ###############
current_time = datetime.datetime.now()
print(current_time) # Current time
print(current_time.replace(microsecond=0)) # Remove microseconds
future_time = current_time + datetime.timedelta(days=12) # Add 12 days
print(future_time)
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# Section 3: Time Type Conversion
timestamp = 1668139932
formatted_time = time.strftime('%Y-%m-%d %X', time.localtime(timestamp))
print('Seconds-level timestamp to formatted string: ' + formatted_time)
ms_timestamp = 1668139932000
sec_timestamp = ms_timestamp / 1000
formatted_ms_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(sec_timestamp))
print('Milliseconds-level timestamp to formatted string: ' + formatted_ms_time)
time_str = '2022-11-11 12:12:12'
time_array = time.strptime(time_str, '%Y-%m-%d %X')
timestamp_converted = int(time.mktime(time_array))
print(f'Time string: {time_str}')
print(f'Time array: {time_array}')
print(f'Timestamp (seconds): {timestamp_converted}')
print('Formatted string time to timestamp (seconds):' + str(timestamp_converted))
# Other formats
print(time.asctime()) # Similar to time.strftime(), fixed format
print(time.ctime()) # Convert timestamp to fixed string format
print(datetime.datetime.now())
print(datetime.datetime.utcnow()) # UTC time
print(datetime.datetime.fromtimestamp(1668139932)) # Fixed format from timestamp
Acquiring Timestamps in Seconds, Milliseconds, and Microseconds
import time
import datetime
# Get timestamps
current_ts = time.time()
secs = int(current_ts) # Seconds
millisecs = int(round(current_ts * 1000)) # Milliseconds
microsecs = int(round(current_ts * 1000000)) # Microseconds
# Convert seconds timestamp to date
date_from_secs = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(secs))
# Format conversions
datetime_new1 = datetime.datetime.strptime(date_from_secs,'%Y-%m-%d %H:%M:%S').strftime('%Y/%m/%d %H:%M:%S')
datetime_new2 = datetime.datetime.strptime(date_from_secs,'%Y-%m-%d %H:%M:%S').strftime('%m/%d/%Y %H:%M')
datetime_new3 = datetime.datetime.strptime(datetime_new2,'%m/%d/%Y %H:%M').strftime('%Y-%m-%d %H:%M:%S')
# String to datetime conversion
str_to_datetime = datetime.datetime.strptime('2022-03-25 11:23:03', "%Y-%m-%d %H:%M:%S")
datetime_to_str = str_to_datetime.strftime("%Y-%m-%d %H:%M:%S")
# Print results
print(f'Original time value = {current_ts}')
print(f'Seconds timestamp = {secs}')
print(f'Milliseconds timestamp = {millisecs}')
print(f'Microseconds timestamp = {microsecs}')
print(f'-----------------------------')
print(f'Seconds timestamp to date = {date_from_secs}')
print(f'Datetime format 1 = {datetime_new1}')
print(f'Datetime format 2 = {datetime_new2}')
print(f'Datetime format 3 = {datetime_new3}')
print(f'-----------------------------')
print(f'String to datetime = {str_to_datetime}, type = {type(str_to_datetime)}')
print(f'Datetime to string = {datetime_to_str}, type = {type(datetime_to_str)}')
Current Date and Time Rterieval
current_dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
current_dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') # Including microseconds
year = datetime.datetime.now().strftime('%Y')
month = datetime.datetime.now().strftime('%m')
day = datetime.datetime.now().strftime('%d')
year_month = datetime.datetime.now().strftime('%Y%m')
year_month_day1 = datetime.datetime.now().strftime('%Y%m%d')
year_month_day2 = datetime.datetime.now().strftime('%Y-%m-%d')
year_month_day3 = datetime.datetime.now().strftime('%Y/%m/%d')
print(f'Current time = {current_dt}')
print(f'Current time with microseconds = {current_dt_ms}')
print(f'Year = {year}')
print(f'Month = {month}')
print(f'Day = {day}')
print(f'Year-Month = {year_month}')
print(f'Year-Month-Day = {year_month_day1}')
print(f'Year-Month-Day = {year_month_day2}')
print(f'Year-Month-Day = {year_month_day3}')
Date Calculasions and Adjustments
from datetime import date, timedelta
def add_months(start_date, months):
"""
:param start_date: Initial date
:param months: Number of months to add
:return: Resulting date after adding months
"""
year_add = months // 12
month = start_date.month + months % 12
if month > 12:
year_add += month // 12
month = month % 12
return date(start_date.year + year_add, month, start_date.day)
# Example usage
print(add_months(date(2022, 3, 24), 5)) # Adding 5 months to March 24, 2022