First Get the Shifted Time
Dealing with times is tricky, so I encourage you to use library calls to do the work for you wherever possible. Time-math gets really messy, really fast.
from datetime import datetime, timedelta original_time = datetime.now() # datetime.datetime(2015, 5, 11, 12, 32, 46, 246004) print(original_time) # 2015-05-11 12:32:46.246004 offset = timedelta(hours=12) # datetime.timedelta(0, 43200) shifted_time = original_time + offset # datetime.datetime(2015, 5, 12, 0, 32, 46, 246004) print(shifted_time) # 2015-05-12 00:32:46.246004 Then Read What You Need
With the time shifted, you can easily read any part of the time, on either the original time, or the new time:
>>>original_time print# original_timedatetime.hour datetime(2015, 5, 11, 12, 32, 46, 246004) >>>original_time.hour print# 12 original_time.year 2015 >>> print# 2015 original_time.month 5 >>> print# 5 original_time.day 11 >>> print# 11 original_time.hour 12 >>> print# 12 original_time.minute 32 >>> print# 32 original_time.second 46 >>> # 46 Then Format and Print
Looking at the Datetime Documentation shows you that the ranges for the values are as follows:
MINYEAR <= year <= MAXYEAR 1 <= month <= 12 1 <= day <= number of days in the given month and year 0 <= hour < 24 0 <= minute < 60 0 <= second < 60 Then Format and Print
If you need another behaviour for printing, use strftimestrftime, as you have been.
datetime.strftime(original_time, "%I") # '12' datetime.strftime(original_time, "%I:30%p") # '12:30PM' datetime.strftime(shifted_time, "%I:30%p") # '12:30AM' datetime.strftime(shifted_time, "%Y %H %M %S") # '2015 00 32 46' datetime.strftime(original_time, "%Y %H %M %S") # '2015 12 32 46' Key Points
Time Math
Be aware of are timedelta which allows you to easily perform math on times and dates. Operations are as simple as t1 = t2 + t3 and t1 = t2 - t3 to add or subtract times.
Formatting
Use strftime to output your datetime in the desired format.