Date Time Functions
Python has a module named datetime to work with dates and times. Let's create a few simple programs related to date and time before we dig deeper.
Example 1: Get Current Date and Time
2019-05-19 09:26:03.478039
Example 2: Get Current Date
2019-05-19
Example 3: Date object to represent a date
2019-04-13
Example 4: Get current date
2019-05-19
Timestamp is the number of seconds between a particular date and January 1, 1970 at UTC
1 day = 86400 seconds
10 day = 864000 seconds
100 day = 8640000 seconds
Example 5: Get date from a timestamp
Date = 2012-01-11
Example 6: Print today's year, month and day
Current year: 2019
Current month: 5
Current day: 19
Example 7: Time object to represent time
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
Example 8: Print hour, minute, second and microsecond
hour = 11
minute = 34
second = 56
microsecond = 0
Example 9: Python datetime object
2018-11-28 00:00:00
2017-11-28 23:55:59.342380
Example 10: Print year, month, hour, minute and timestamp
year = 2017
month = 11
day = 28
hour = 23
minute = 55
timestamp = 1511913359.34238
Example 11: Difference between two dates and times
t3 = 201 days, 0:00:00
t6 = -333 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>
Example 12: Difference between two timedelta objects
t3 = 14 days, 13:55:39
Example 13: Printing negative timedelta object
t3 = -1 day, 23:59:39
t3 = 0:00:21
Handling timezone in Python
Local: 04/23/2020, 12:00:11
NY: 04/23/2020, 02:30:11
London: 04/23/2020, 07:30:11
Last updated
Was this helpful?