Python date/time format conversion
In this post, you will learn how to use the Python datetime
module to convert time data to a desired format or type, as shown below.
- Convert time to minutes seconds
- Convert time to a Unix timestamp int number
- Convert to UTC time
- Convert time from a dataframe
- Convert to a string
1. Convert Time to Seconds
If you want to convert a time to seconds, you can use the total_seconds()
method of a timedelta
object.
from datetime import datetime, timedelta
# create timedelta object
td = timedelta(hours=2, minutes=30)
seconds = td.total_seconds()
print(f"Total seconds: {seconds}")
2. Convert Time to Minutes
Likewise, to convert time to minutes, you can divide the result of the total_seconds()
method by 60.
minutes = seconds / 60
print(f"Total minutes: {minutes}")
3. Convert Datetime to Integer
To convert a datetime
object to a Unix timestamp, you can use the timestamp()
method.
timestamp = int(dt.timestamp())
print(f"Unix timestamp: {timestamp}")
4. Convert Datetime to UTC
To convert a datetime
object to UTC, you can use the astimezone()
method with the pytz
library.
import pytz
utc_time = dt.astimezone(pytz.utc)
print(f"UTC time: {utc_time}")
5. Convert Time Format in DataFrame
To convert the time format in a Pandas DataFrame, you can use the pd.to_datetime()
function.
import pandas as pd
# data with date and time
data = {'date_time': ['2023-07-07 10:30', '2023-07-08 11:45', '2023-07-09 12:50']}
df = pd.DataFrame(data)
# convert string to datetime object
df['date_time'] = pd.to_datetime(df['date_time'])
print(df)
6. Convert Datetime to String
You can convert a datetime
object to a string using the strftime()
method.
date_str = dt.strftime("%Y-%m-%d %H:%M:%S")
print(f"Date string: {date_str}")
Conclusion
Python's datetime
module is very effective for time conversion tasks. In this post, we've seen how to utilize the functionalities of the datetime
module for time conversion. By leveraging these features, you can handle time conversion tasks more easily and efficiently.
