CyberKeeda In Social Media
Showing posts with label strftime. Show all posts
Showing posts with label strftime. Show all posts

How to use, Python's DateTime Module

 


Python's Date Time Module:
    Python's datetime module ships with default python package which you can't skip for sure sooner or later you will come to know about it.
This module will help you to verify multiple checks and algorithms based upon date time filter.

I will keep on updating the post as per my learnings and used in practical scenarios.
Let's go through it :)

Basic Usage of date time
  • Import module and display current date.

Syntax
# Import datetime function from datetime library
from datetime import datetime
datetime.datetime(2021, 6, 7, 2, 43, 32, 276412)

# Create object and store value##
  dt = datetime.now()
# Display date, time without Formatting
print(dt)

Output:

datetime.datetime(2021, 6, 7, 2, 43, 32, 276412)


Filter datetime output as per our requirement.
  • Filter date

Syntax
# dt = datetime.now()
# show_date = dt.date()

# print (show_date)

Output:

datetime.date(2021, 6, 7)

Filter only Day

# dt = datetime.now()
# show_day = dt.day

# print (show_day)

Output:

7

  • Filter Month

Syntax
# dt = datetime.now()
# show_month = dt.month

# print (show_month)

Output:

6

Use datetime strftime to format date/time as per our need

    Below are some identifier to use while formatting.
    • %a  : Day of week (Short )
      • Mon, Tue, Wed, ... Sat, Sun
    • %A : Day of week (Full )
      • Monday, Tuesday, Wednesday .. Saturday, Sunday
    • %m : Month  ( Two digit number )
      • 01,02,03,04 .... 10,11,12
    • %y : Year ( Short, Two digit number )
      • 19,20,21
    • %Y : Year ( Full)
      • 2019,2020,2021
    • %d : Date ( Two digit number )
      • 01,02,03,04, 22,23,30,31

    Use Strftime as per our need.
    • With or Without Variables


    Syntax
    # dt = datetime.now()
    # show_val1 = dt.strftime('%m%d%y')
    # show_val2 = dt.strftime('%m%d%Y')
    # show_val3 = dt.strftime('%Y%m%d')
    # show_val4 = dt.strftime('%a %m %y')
    # show_val5 = dt.strftime('%A-%m-%Y')
    # show_val6 = dt.strftime('%I %p %S')
    # show_val7 = dt.strftime('%-j')
    # show_val8 = dt.strftime('myprefix-%m%d%y-mysuffix')

    # print (show_val1)
    # print (show_val2)
    # print (show_val3)
    # print (show_val4)
    # print (show_val5)
    # print (show_val6)
    # print (show_val7)

    Output:

    060721
    06072021
    20210607
    Mon 06 21
    Monday-06-2021
    02 AM 32
    158
    myprefix-060721-mysuffix


    There is lot of content with respect to datetime module, will keep this post updated ;)
    Read more ...
    Designed By Jackuna