[Python] Class type and usage of datetime module

[Note] Class type and usage of python datetime module

Check the types and differences of classes that can be used in the datetime module of python with an example.

Official site

Class type

6 types of classes (data types) are available

  1. datetime.date: Date (year, month, day)
  2. datetime.time: Time (hours, minutes, seconds, microseconds)
  3. datetime.datetime: date + time
  4. datetime.timedelta: time difference
  5. datetime.timezone: Time zone setting
  6. datetime.tzinfo: Time zone information

Contents of each class

0. Supplementary conditions

Call the datetime module as dt.

Call the datetime module


import datetime as dt

▼ Actual usage example datetime.date is written as dt.date

  • Datetime.datetime.date will result in an error (name 'datetime' is not defined)
  1. datetime.date

Execution result of dt.date.today () datetime.date(2020, 3, 18) └ datetime.date type └ (2020, 3, 18) = (year, month, day)

⇒ ** You can get 3 data of year, month and day **. (Attributes: year, month, day)


2. datetime.time It seems that the method cannot be used with `dt.time`. .. Like dt.date, I can't get the current time.

--dt.time.now (): error --dt.time.today (): Error

type object 'datetime.time' has no attribute 'today'

** ■ How to use ** Specify the time yourself.

This is effective when you do not need date data and want to call or change only time data.

--Specify hours, minute, second, microsecond individually of datetime.time type. --Call the specified data. (Example: .hour) --Change the specified data (Example: .replace (hour = 1))

Specified number

Specifying and calling the time (datetime).time)



#Set the time
timeA = dt.time(10, 30, 45, 123456) 

#Call the time
timeA.hour  #Execution result: 10
timeA.minute #Execution result: 30
timeA.second #Execution result: 45
timeA.microsecond #Execution result: 123456

Change the time (replace)())


#Set the time
timeA = dt.time(10, 30, 45, 123456) 

#(1)Change individually
timeA = timeA.replace(hour=5)  
timeA

#Execution result
# → datetime.time(5, 30, 45, 123456) 


#(2)Change all at once
timeA = timeA.replace(hour=1, minute=2, second=30, microsecond=400)
timeA

#Output result
# → datetime.time(1, 2, 30, 400)

3. datetime.datetime

Execution result of dt.datetime.today () datetime.datetime(2020, 3, 18, 7, 42, 54, 95450) └ datetime.datetime type   └ (2020, 3, 18, 7, 42, 54, 95450) (Year, month, day, hour, minute, second, microsecond)

⇒ ** You can get 7 data of year, month, day, hour, minute, second, and microsecond **. (Attributes: year, month, day, hour, minute, microsecond)

  • I also have tzinfo (tz: time zone information) on the back side.

** ▼ tzinfo (tz: time zone information) ** Information is output when the method is executed with now without parentheses.

Display time zone information


dt.datetime.now
<function datetime.now(tz=None)>

** ■ now () and today () ** datetime. A method often used in datetime. * Both are the same

Frequently used methods now and today


#.now()
dtNow = dt.datetime.now()
dtNow  #datetime.datetime(2020, 3, 18, 21, 28, 13, 409431)

#.today()
dtToday = dt.datetime.today()
dtToday #datetime.datetime(2020, 3, 18, 22, 45, 10, 518281)


**■combine(A, B)** It is possible to combine the date type and the time type. `datetime.datetime.combine(A, B)`

Frequently used method combine


#.combine(A, B)
dateA = dt.date(2020,5,6)
timeA = dt.time(10,20,0)

dt.datetime.combine(dateA, timeA)

#Output result
# → datetime.datetime(2020, 5, 6, 10, 30, 0)

If it is different from the specified type such as cobmbine (timeA, dateB), an error will occur.

combine() argument 1 must be datetime.date, not datetime.time


**■replace()** The numerical value specified by the argument can be changed (multiple can be specified)

replace


#.replace()

dtNow =dt.datetime.now() 
dtNow # datetime.datetime(2020, 3, 18, 22, 10, 15, 517216)

dtNow = dtNow.replace(year=2018)
dtNow = dtNow.replace(hour=5, minute=30, second=30)
dtNow

#Output result
# → datetime.datetime(2018, 3, 18, 5, 30, 30, 474609)

** ■ Output the day of the week ** weekday (): 0-6 (Monday 0-Sunday 6) ʻIsoweekday ()`: 1-6 (Monday 1-Sunday 7)

output Month fire water wood Money soil Day
weekday() 0 1 2 3 4 5 6
isoweekday() 1 2 3 4 5 6 7

Day of the week output


today = dt.datetime.today()  #datetime.datetime(2020, 3, 18, 22, 30, 46, 646567)

#.weekday()
today.weekday() #Output: 2 → Wednesday

#.isoweekday()
today.weekday() #Output: 3 → Wednesday

** ■ Output only date or time ** date() :year、month、day time() :hour、minute、second、microsecond

Date / time output


now = dt.datetime.now()
#datetime.datetime(2020, 3, 18, 22, 35, 50, 177279)

#.time()
now.time() #Output: datetime.time(22, 38, 1, 997649)

#.date()
now.date() #datetime.date(2020, 3, 18)

4. datetime.timedelta ・ You can add and subtract dates and times. -The result of subtracting dates is displayed as timedelta.

--Timedelta does not add or subtract. -** ★ Specify which item to add / subtract how many ** --dt.timedelta (days = 2): Add 2 days --dttimedelta (hours = -5): subtract 5 hours --Specifiable arguments (7 types. ** * Plural ** --weeks (: multiple of 7days) - days - hours - minutes - seconds - milliseconds - microseconds --Arguments that cannot be specified (** year and month are not possible **) - years - months --Default argument is 0

Unspecified arguments or incorrect arguments (singular, etc.) will result in an error

'years' is an invalid keyword argument for __new__()

** How to use ** (1) Add 2 weeks to January 1, 2020 + dt.timedelta(weeks=2)

Add with timedelta


newyear = dt.datetime(2020, 1, 1)  #Define January 1, 2020 as datetime type
newyear + dt.timedelta(weeks=2)

#Execution result
#datetime.datetime(2020, 1, 15, 0, 0)
#→ January 15, 2020

(2) 25 hours subtracted from January 1, 2020 `+ dt.timedelta(hours=-25)`

Subtract with timedelta


newyear = dt.datetime(2020, 1, 1)  #Define January 1, 2020 as datetime type
newyear + dt.timedelta(hours=-25)

#Execution result
datetime.datetime(2019, 12, 30, 23, 0)
#→ December 30, 2019 23:00

** Supplement ** (3) Data parts that you do not have are also ** calculated **

** ▼ Example ** -No error occurs even if time is added to date type (which does not have time data). ・ The calculated result is displayed. └ Calculated in the hidden part

Handling of data that the mold does not have


newyear2 = dt.date(2020, 1, 1)  #datetime.date type (does not have time data)
newyear2 + dt.timedelta(hours=100) #Add 100 hours

#Execution result
#datetime.date(2020, 1, 5)
#→ January 5, 2020

(3) Date difference result Calculate the interval between dates.

--The types that can be used are datetime.datetime and datetime.date. --datetime.time cannot be used --The ones to compare need to be the same --Error occurs with datetime.datetime and datetime.date --Cannot add (error)

Find the interval between two dates (Case 1)


dateA = dt.date(2020,1,1)
dateB = dt.date(2020,1,9)

dateA - dateB  #Output: datetime.timedelta(days=-8)
dateB - dateA  #Output: datetime.timedelta(days=8)

Find the interval between two dates(Case 2)


pastA = dt.datetime(2000, 1, 1)
now = dt.datetime.now()  #Output: datetime.datetime(2020, 3, 18, 22, 56, 50, 604259)

now - pastA

#Output result
#datetime.timedelta(days=7382, seconds=82358, microseconds=594717)

Addition is an error (* "+" is not supported)

unsupported operand type(s) for +


5. datetime.timezone Used when setting the time zone by yourself.

dt.timezone(dt.timedelta(hours=AAA), 'BBB')

There are two values to set.

--AAA: How much does it deviate from the standard? -+/- 0 ~ 24 * 24 or less --24 is an error --BBB: Name given to the set time zone --Use as an argument when calling

** ▼ Setting method ** ① United Kingdom (UCT. Standard: +0 hours) [≒ GMT] datetime.timezone(datetime.timedelta(0), 'UCT')

② Toronto (EDT.-4) datetime.timezone(datetime.timedelta(-4), 'EST')

③ Japan (JST. +9) dt.timezone(dt.timedelta(hours=+9), 'JST')

** ▼ Example of actual usage ** Set the time in Toronto (EDT) and recall the current time.

How to use timezone(Toronto time)


EDT = dt.timezone(dt.timedelta(hours=-4),'EDT')
EDT #Output: datetime.timezone(datetime.timedelta(days=-1, seconds=72000), 'EDT')

dt.datetime.now(EDT)

#Output result
# datetime.datetime(2020, 3, 18, 10, 34, 8, 685415, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000), 'EDT'))

** ■ Supplement: Difference between UTC and GMT **

** ① UTC: Coordinated Universal Time ** └ Current Coordinated Universal Time └ Calculated from the frequency of cesium atoms

** ② GMT: Greenwich Mean Time ** └ Past standard time └ Calculated from the measurement results of the Greenwich Observatory └ Greenwich is a city just south of London

-Neither is much different (UTC ≒ GMT) --British time --UK is the standard: hours = ± 0


6. datetime.tzinfo It provides the concept of ** customizable time adjustment ** such as time zone and daylight saving time (he said).

Recommended Posts

[Python] Class type and usage of datetime module
[Python] Class type and usage of datetime module
I tried using the Datetime module by Python
Usage of Python locals ()
[Python] Create a list of date and time (datetime type) for a certain period
Python --Explanation and usage summary of the top 24 packages
[Python] Type Error: Summary of error causes and remedies for'None Type'
[python] Calculation of months and years of difference in datetime
Summary of date processing in Python (datetime and dateutil)
[Python] Correct usage of map
Python: Class and instance variables
Automatic update of Python module
Python --Check type of values
About Python datetime and timezone
Python debug and test module
Sample usage of Python pickle
Basic usage of Python f-string
[Python] Correct usage of join
Source installation and installation of Python
[Python of Hikari-] Chapter 08-03 Module (Import and use of standard library)
Reference order of class variables and instance variables in "self. Class variables" in Python
Environment construction of python and opencv
The story of Python and the story of NaN
perl objects and python class part 2.
Installation of SciPy and matplotlib (Python)
[Python of Hikari-] Chapter 09-03 Class (inheritance)
[python] week1-3: Number type and operation
Cooperation between python module and API
[Code] Module and Python version output
Calculation of homebrew class and existing class
This and that of python properties
Python3 socket module and socket communication flow
Installation and easy usage of pytest
perl objects and python class part 1.
[python] Correct usage of if statement
Coexistence of Python2 and 3 with CircleCI (1.0)
Summary of Python indexes and slices
Reputation of Python books and reference books
[Python] Basic pattern and usage of if statement (comparison operator and Boolean operator)
Specify your own class in class argument and return type annotation in Python
Installation of Visual studio code and installation of python
Conversion of string <-> date (date, datetime) in Python
[Learning memo] Basics of class by python
Example of using class variables and class methods
Pass the path of the imported python module
[Python] Visualize the heat of Tokyo and XX prefectures (DataFrame usage memo)
Implementation module "deque" in queue and Python
Comparison of Japanese conversion module in Python3
Extraction of tweet.js (json.loads and eval) (Python)
Make a relation diagram of Python module
Connect a lot of Python or and and
Coexistence of Flask logging and other module logging
Python basic operation 3rd: Object-oriented and class
[Python] Difference between class method and static method
Comparison of class inheritance and constructor description
Receive date type (datetime) with ArgumentParser [python]
[python] [meta] Is the type of python a type?
Non-logical operator usage of or in python
Easy introduction of python3 series and OpenCV3
[Python] Various combinations of strings and values
Python and NumPy numeric type inheritance relationship
Module import and exception handling in python