Python Date and TimePython gives the developer several tools for working with date and time . The standard libraries contains the modules such as:
datetime ObjectDatetime objects are probably one of the most used in any application. A datetime object is an instance of the datetime.datetime class that represents a single point in time. The datetime module includes functions and classes for doing date and time parsing, formatting, and arithmetic. So the datetime module can be imported like this:
How to get current time in Python?
import datetime print(datetime.datetime.now())
Calendar date values are represented with the date class. Instances have attributes for year, month, and day.example
import datetime today = datetime.datetime.now() print("Day : ", today.day) print("Month : ", today.month) print("Year : ", today.year) print("Hour : ", today.hour) print("Minute : ", today.minute) print("Second : ", today.second)
Time values are represented with the time class. Times have attributes for hour, minute, second, and microsecond.
Getting current timeexample
import time; ltime = time.localtime(time.time()) print ("Local current time :", ltime)
Format the current time in PythonYou can format any time as per your requirement, but a simple method can do so by calling time.strftime(format[, t]) with the current time object as the argument t. If the t argument is not provided or None, then the time_struct object returned by time.localtime is used. example
import time; ltime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", ltime)
calendar objectPython has a built-in function, calendar to work with date related tasks. It defines the Calendar class , which encapsulates calculations for values such as the dates of the weeks in a given month or year. example
import calendar year = 2010 month = 10 print(calendar.month(year, month))output
October 2010 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
- Python Exception Handling
- How to Generate a Random Number in Python
- How to pause execution of program in Python
- How do I parse XML in Python?
- How to read and write a CSV files with Python
- Threads and Threading in Python
- Python Multithreaded Programming
- Python range() function
- How to Convert a Python String to int
- Python filter() Function
- Difference between range() and xrange() in Python
- How to print without newline in Python?
- How to remove spaces from a string in Python
- How to get the current time in Python
- Slicing in Python
- Create a nested directory without exception | Python
- How to measure time taken between lines of code in python?
- How to concatenate two lists in Python
- How to Find the Mode in a List Using Python
- Difference Between Static and Class Methods in Python?