Intern — Junior
What methods and data types exist for working with timestamps and dates in programming?
sobes.tech AI
Answer from AI
In Python, the most commonly used modules for working with dates and timestamps are datetime and time.
Main types and methods:
datetime.datetime— an object representing date and time.datetime.date— an object with only the date (year, month, day).datetime.time— an object with only the time (hours, minutes, seconds).datetime.timedelta— the difference between two dates or times.
Example of creating the current date and time:
from datetime import datetime
now = datetime.now()
print(now) # 2024-06-01 12:34:56.789012
To work with timestamps:
import time
timestamp = time.time() # number of seconds since January 1, 1970
print(timestamp)
Converting timestamp to date:
dt = datetime.fromtimestamp(timestamp)
print(dt)
Thus, these tools allow for convenient creation, conversion, and calculation of dates and times in Python programs.