Saturday, December 28, 2024
Google search engine
HomeLanguagesPython Date and Time

Python Date and Time

Python Time & Date example; In this tutorial, you will learn how to display current date, time, month, year , second, minutes, hours, and millisecond in python using date time module.

.medrectangle-3-multi-320{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:auto!important;margin-right:auto!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:250px;padding:0;text-align:center!important;width:100%}

Python Date and Time

First of all, you need to know about the python DateTime module. Python has a module named DateTime to work with dates and times.

1: How do you display current date and time in python?

Import DateTime module in your python program. Then you can use now() method to create a datetime object containing the current local date and time.

#import datetime module
]import datetime

datetime_object = datetime.datetime.now()
print(datetime_object)

After executing the program, the output will be something like:

 2020-04-26 11:00:45.188915 

In the above python program, we have imported datetime module using import datetime statement. One of the classes defined in the datetime module is datetime class. Then we used now() method to create a datetime object containing the current local date and time.

2: How do I get the current date in python?

Import datetime module in your python program. And you can use today() method defined in the date class to get a date object containing the current local date.

import datetime

date = datetime.date.today()
print('Today is ', date)

After executing the program, the output will be something like:

 Today is 2020-04-26 

In this program, we have used today() method defined in the date class to get a date object containing the current local date.

What’s inside datetime?

You can use python dir() function to get a list containing all properties of a module. You can see the program below:

import datetime

print(dir(datetime))

After executing the program, the output will be:

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

3: Date object to represent a date

import datetime

d = datetime.date(2020, 4, 13)
print(d)

After executing the program, the output will be:

2020-04-13

4: Get current date

You can create a date object containing the current date by using a classmethod named today(). Here’s how:

from datetime import date

today = date.today()

print("Current date =", today)

After executing the program, the output will be:

 Current date = 2020-04-26 

5: Get date from a timestamp

We can also create date objects from a timestamp. A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at UTC. You can convert a timestamp to date using fromtimestamp() method.

from datetime import date

timestamp = date.fromtimestamp(1326244364)

print("Date =", timestamp)

After executing the program, the output will be:

Date = 2012-01-11

6: Print today’s year, month and day

Get year, month, day, day of the week etc. from the date object. See the following python program:

from datetime import date

# date object of today's date
today = date.today() 

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

After executing the program, the output will be:

Current year: 2020
Current month: 4
Current day: 26

7: Time object to represent time

from datetime import time

# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)

# time(hour, minute and second)
b = time(12, 34, 56)
print("b =", b)

# time(hour, minute and second)
c = time(hour = 9, minute = 34, second = 56)
print("c =", c)

# time(hour, minute, second, microsecond)
d = time(1, 34, 56, 234566)
print("d =", d)

After executing the program, the output will be:

a = 00:00:00 
b = 12:34:56 
c = 09:34:56 
d = 01:34:56.234566 

8: Show hour, minute, second and microsecond

Once you create a time object in your python programs, you can easily display its properties such as hour, minute etc.

from datetime import time

a = time(11, 34, 56)

print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)

After executing the python program, the output will be:

hour = 11
minute = 34
second = 56
microsecond = 0

Note:- The microsecond default value 0.

9: Python datetime object

from datetime import datetime

#datetime(year, month, day)
a = datetime(2018, 11, 28)
print(a)

# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)

After executing the program, the output will be:

2018-11-28 00:00:00 2017-11-28 23:55:59.342380 

10: Print year, month, hour, minute and timestamp

from datetime import datetime

a = datetime(2020, 10, 30, 23, 55, 59, 342380)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
print("timestamp =", a.timestamp())

After executing the program, the output will be:

year = 2020
month = 10
hour = 23
minute = 55
timestamp = 1604102159.34238

11: Difference between two dates and times

from datetime import datetime, date

t1 = date(year = 2020, month = 9, day = 11)
t2 = date(year = 2019, month = 8, day = 25)

t3 = t1 - t2

print("t3 =", t3)

t4 = datetime(year = 2020, month = 8, day = 11, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 5, day = 12, hour = 5, minute = 55, second = 13)

t6 = t4 - t5

print("t6 =", t6)

print("type of t3 =", type(t3)) 
print("type of t6 =", type(t6))  

After executing the program, the output will be:

t3 = 383 days, 0:00:00
t6 = 457 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>

12: Difference between two timedelta objects

from datetime import timedelta

t1 = timedelta(weeks = 6, days = 9, hours = 1, seconds = 33)
t2 = timedelta(days = 2, hours = 15, minutes = 4, seconds = 54)

t3 = t1 - t2

print("t3 =", t3)

After executing the program, the output will be:

 t3 = 48 days, 9:55:39 

13: Time duration in seconds

You can get the total number of seconds in a timedelta object using total_seconds() method.

from datetime import timedelta

t = timedelta(days = 8, hours = 1, seconds = 33, microseconds = 233423)
print("total seconds =", t.total_seconds())

After executing the program, the output will be:

 total seconds = 694833.233423 

Python format datetime

The way dates and times are represented may vary in different places, organizations, etc. Using mm / dd / yyyy is more common in the US, while dd / mm / yyyy is more common in the UK.

Python has strftime() and strptime() methods to handle this.

Python strftime() – datetime object to string

The strftime() method is defined under classes datedatetime and time. The method creates a formatted string from a given datedatetime or time object.

Example 1: Format date using strftime()

from datetime import datetime

# current date and time
now = datetime.now()

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

After executing the program, the output will be something like:

time: 11:33:14
s1: 04/26/2020, 11:33:14
s2: 26/04/2020, 11:33:14

Here, %Y%m%d%H etc. are format codes. The strftime() method takes one or more format codes and returns a formatted string based on it.

In the above program, t, s1 and s2 are strings.

  • %Y – year [0001,…, 2018, 2019,…, 9999]
  • %m – month [01, 02, …, 11, 12]
  • %d – day [01, 02, …, 30, 31]
  • %H – hour [00, 01, …, 22, 23
  • %M – minute [00, 01, …, 58, 59]
  • %S – second [00, 01, …, 58, 59]

To learn more about strftime() and format codes, visit: Python strftime().

Python strptime() – string to datetime

The strptime() method creates a datetime object from a given string (representing date and time).

Example 1: strptime()

from datetime import datetime

date_string = "25 May, 2020"
print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)

After executing the program, the output will be:

 date_string = 25 May, 2020
 date_object = 2020-05-25 00:00:00 

The strptime() method takes two arguments:

  1. a string representing date and time
  2. format code equivalent to the first argument

By the way, %d%B and %Y format codes are used for day, month(full name) and year respectively.

Visit Python strptime() to learn more.

Handling timezone in Python

Assume, you are working on a project and need to represent the date and time based on their timezone. Instead of trying to handle the timezone yourself, we suggest you to use a third-party pytZ module.

from datetime import datetime
import pytz

local = datetime.now()
print("Local:", local.strftime("%m/%d/%Y, %H:%M:%S"))


tz_NY = pytz.timezone('America/New_York') 
datetime_NY = datetime.now(tz_NY)
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))

tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London:", datetime_London.strftime("%m/%d/%Y, %H:%M:%S"))

After executing the program, the output will be something like:

Local: 04/26/2020, 11:37:11
Local: 04/26/2020, 11:37:11
NY: 04/26/2020, 07:37:12
NY: 04/26/2020, 07:37:12
London: 04/26/2020, 12:37:12
London: 04/26/2020, 12:37:12

According to the respective timezone, datetime_NY and datetime_London are datetime objects containing the current date and time.

Recommended Python Programs

  1. Python Program to Add Two Numbers
  2. Python Program to Find/Calculate Sum of n Numbers
  3. Python Program to Find/Calculate Average of 3, 4, 5…n numbers
  4. Python Program to Print ASCII Value of Character
  5. Write a Program to Calculate Simple Interest in Python
  6. Python Program to Compute Compound Interest
  7. Leap Year Program in Python
  8. How to Check Whether a Number is Fibonacci or Not in Python
  9. Python: Program to Find Power of Number
  10. Python Program to Reverse a Numbers
  11. Python Program to Find Smallest/Minimum of n Numbers
  12. Python Program to Find Largest/Maximum of n Numbers
  13. Python Program to Find The Net Bill Amount After Discount
  14. Python Program to Print Numbers From N to 1 and 1 to N
  15. Python Program to Print Numbers Divisible by 3, 5, 7
  16. Python Program to Print Prime Number 1 to N
  17. How to Find Square of Number in Python
  18. Python Program to Calculate Cube of Number
  19. Python Program to Find LCM of Two Numbers
  20. BMI (Body Mass Index) Calculator in Python
  21. Palindrome Program in Python using while loop, Function, etc
  22. Python: Program to Count Total Number of Bits in Number
  23. Python Random Number Generator Code
  24. Python Program to Swap Two Numbers
  25. Python Program to Get Standard Deviation
  26. Python Program to Find the Variance
  27. Python Program to Convert Height in cm to Feet and Inches
  28. Python Program to Convert Meters into Yards, Yards into Meters
  29. Python Program to Convert Kilometers to Meters, Miles
  30. Python Program to Find Perfect Number
  31. Python: Program to Find Strong Number
  32. Python Program Create Basic Calculator
  33. Python Program For math.floor() Method
  34. Python Program to Find Sum of Series 1/1! 2/2! 3/3! …1/n!
  35. Python: Program to Convert Decimal to Binary, Octal and Hexadecimal
  36. Python Program to Find Roots of Quadratic Equation
  37. Python Program to Print Alphabets from A to Z in Uppercase and Lowercase
  38. Python Program to Check Given Input is Alphabet, Number or Special Character
  39. Python Program to Calculate Area of Triangle
  40. Python Program to Find Area and Circumference of Circle using Radius
  41. Python Program that Accepts Marks in 5 Subjects and Outputs Average Marks
  42. Python Program to Print Binary Value of Numbers From 1 to N
RELATED ARTICLES

Most Popular

Recent Comments