Appearance
datetime
The datetime
module is the standard library for handling dates and times in Python.
Getting Current Date and Time
To obtain the current date and time:
python
from datetime import datetime
now = datetime.now() # Get current datetime
print(now)
print(type(now)) # <class 'datetime.datetime'>
datetime
is both a module and a class within that module. If you import it directly, you access the class.
Specifying a Date and Time
You can create a datetime
object using specific parameters:
python
dt = datetime(2015, 4, 19, 12, 20) # Create datetime with specified date and time
print(dt) # 2015-04-19 12:20:00
Converting datetime to Timestamp
To convert a datetime
object to a timestamp, use the timestamp()
method:
python
timestamp = dt.timestamp() # Convert datetime to timestamp
print(timestamp) # 1429417200.0
Converting Timestamp to datetime
To convert a timestamp back to a datetime
object:
python
t = 1429417200.0
print(datetime.fromtimestamp(t)) # Local time
print(datetime.utcfromtimestamp(t)) # UTC time
Converting String to datetime
To convert a string representation of date and time into a datetime
object:
python
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
print(cday) # 2015-06-01 18:19:59
Converting datetime to String
To format a datetime
object as a string:
python
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M')) # Mon, May 05 16:28
datetime Arithmetic
You can perform arithmetic operations on datetime
using the timedelta
class:
python
from datetime import timedelta
now + timedelta(hours=10) # Add 10 hours
now - timedelta(days=1) # Subtract 1 day
Local Time to UTC Time
You can assign a timezone to a datetime
object using the timezone
class:
python
from datetime import timezone
tz_utc_8 = timezone(timedelta(hours=8))
dt = now.replace(tzinfo=tz_utc_8)
Timezone Conversion
To convert between timezones, you can use astimezone()
:
python
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) # Beijing time
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9))) # Tokyo time
Summary
datetime
requires timezone information for specific time representation. It’s best to store datetime
as a timestamp, which is timezone-independent.
Exercise
Create a function to convert user-input date and time with timezone information into a timestamp:
python
def to_timestamp(dt_str, tz_str):
pass
# Test:
t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
assert t1 == 1433121030.0, t1
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
assert t2 == 1433121030.0, t2
print('ok')