Python: Working with timestamps
To get the current timestamp in Python, you can use the time module's time() function, which returns the current time in seconds since the…
To get the current timestamp in Python, you can use the time module's time() function, which returns the current time in seconds since the epoch (the epoch is a predefined point in time, usually the beginning of the year 1970).
Here’s an example of how you can use it:
import time
current_timestamp = time.time()
print(current_timestamp)This will output the current timestamp in seconds. If you want the timestamp in a different format, you can use the datetime module to convert it.
For example, here’s how you can convert the timestamp to a readable date and time string:
import datetime
# Convert the timestamp to a datetime object
dt = datetime.datetime.fromtimestamp(current_timestamp)
# Format the datetime object as a string
timestamp_str = dt.strftime('%Y-%m-%d %H:%M:%S')
print(timestamp_str)This will output a string in the format 'YYYY-MM-DD HH:MM:SS', such as '2023-01-04 15:29:01'.
To convert a string to a datetime object in Python, you can use the datetime.datetime.strptime() function. This function takes two arguments: the string you want to parse, and the format of the string.
Here’s an example of how you can use it:
import datetime
date_string = '2023-01-04 15:29:01'
date_format = '%Y-%m-%d %H:%M:%S'
# Parse the date string and create a datetime object
dt = datetime.datetime.strptime(date_string, date_format)
print(dt)This will output a datetime object representing the date and time specified in the string. You can then use the object to access the different components of the date and time, such as the year, month, day, hour, minute, and second.
For example:
print(dt.year) # 2023
print(dt.month) # 1
print(dt.day) # 4
print(dt.hour) # 15
print(dt.minute) # 29
print(dt.second) # 1You can find a list of the format codes that can be used in the date_format string in the documentation for the strftime() function:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
In Plain English 🚀
Thank you for being a part of the In Plain English community! Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Discord | Newsletter
- Visit our other platforms: CoFeed | Differ
- More content at PlainEnglish.io