Sunday, October 15, 2023

DateTime in Python

#There is no date data type in python
#To deal with date and time you need to use DateTime built in module of python
        
# For Ex - Current date can be displayed as follow
import datetime as dt   # importing the module

# Note below: datetime represent constructor of datetime class
x = dt.datetime.now()   

print(x)
Output will be in following format:

2023-05-25 16:02:23.115559

Note*: It contains year, month, day, hour, minute, second, and microsecond

DateTime module methods

# There are many methods to give information about date object
# For Ex – Getting the year and name of weekday using current date object
import datetime as dt
x = dt.datetime.now()    # To get current date object
print(x.year)            # To display year

print(x.strftime("%A"))  # To display day name
Output will be like: 
2023
Thursday

Creating Date Objects

# You can create a date object using datetime class constructor of the datetime module 
# And you have to pass three parameters  values: year, month and day in constructor

# The datetime() class also takes parameters for time and timezone (i.e : hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone)
   
# For Ex – Creating a date object
import datetime

x = datetime.datetime(2020, 5, 17)

print(x)
Output will be: 
2020-05-17 00:00:00

The strftime() Method

# This method is used for formatting date objects into readable strings.
# It takes one parameter, format, to specify the format of the returned string

# For Ex – Displaying the name of the month 
import datetime
x = datetime.datetime(2018, 6, 1)   # Creating a specific date object

print(x.strftime("%B"))             # Getting month information from date object
Output will be: 
June

# Few Examples of format code to be pass in strftime() method :

Tags: Technology,Python,

No comments:

Post a Comment