current position:Home>Datetime of pandas time series preamble
Datetime of pandas time series preamble
2022-02-01 13:09:40 【Salted fish Science】
「 This is my participation 11 The fourth of the yuegengwen challenge 26 God , Check out the activity details :2021 One last more challenge 」
Before we study time series, we need to understand datetime Basic use of modules ,datetime Modules are not pandas The library contains .
But in order to learn better pandas Time series in , We can learn first datetime In order to lay a good foundation ,datetime We mainly master several methods :datetime.date(), datetime.datetime(), datetime.timedelta()
datetime.date
We can use datetime.date.today
Method returns the current time , Its data type is datetime.date
import datetime
today = datetime.date.today()
print(today,type(today))
>>>
2018-10-28 <class 'datetime.date'> Copy code
At the same time, we can use datetime.date( year , month , Japan )
Output the date we want datetime type .
import datetime
t = datetime.date(2016,6,1)
print(t)
# ( year , month , Japan ) → Get the date directly
>>>
2016-06-01
Copy code
datetime.datetime
We use datetime.datetime.now
Method returns the current time , Its data type is datetime.datetime
import datetime
now = datetime.datetime.now()
print(now,type(now))
>>>
2018-10-28 17:34:07.467642 <class 'datetime.datetime'> Copy code
In the same way, we can use datetime.datetime( year , month , Japan , when , branch , second )
Output what we want in the form of datetime.datetime
Data of type .
t1 = datetime.datetime(2016,6,1)
t2 = datetime.datetime(2014,1,1,12,44,33)
print(t1,t2)
>>>
2016-06-01 00:00:00 2014-01-01 12:44:33
Copy code
datetime.timedelta
datetime.timedelta
The data represented is the time difference data type . Time difference is mainly used as the addition and subtraction of time , Equivalent to recognizable time “ Difference value ”
# datetime.timedelta: Time difference
today = datetime.datetime.today() # datetime.datetime Also have today() Method
yestoday = today - datetime.timedelta(1) #
print(today)
print(yestoday)
print(today - datetime.timedelta(7))
>>>
2018-11-04 14:48:28.967149
2018-11-03 14:48:28.967149
2018-10-28 14:48:28.967149
Copy code
Date resolution method :parser.parse
In addition to the above conversion method , We also need other methods for parsing strings into time format .
have access to parse Method to convert a string to datetime.datetime
Data of type .
from dateutil.parser import parse
date = '12-21-2017'
t = parse(date)
print(t,type(t))
>>>
2017-12-21 00:00:00 <class 'datetime.datetime'> Copy code
Similarly, we can also convert strings in other formats into datetime.datetime
, But I can't parse Chinese
print(parse('2000-1-1'),'\n',
parse('5/1/2014'),'\n',
parse('5/1/2014', dayfirst = True),'\n',
# In the international common format , The day is before the month , Can pass dayfirst To set up
parse('22/1/2014'),'\n',
parse('Jan 31, 1997 10:45 PM'))
>>>
2000-01-01 00:00:00
2014-05-01 00:00:00
2014-01-05 00:00:00
2014-01-22 00:00:00
1997-01-31 22:45:00
Copy code
Pandas Time data :Timestamp
- The time data represents the point in time , yes pandas Data type of
- It is the most basic type of time series data that associates values with time points .
Timestamp And the above datetime Basically no difference , The only difference from one is pandas modular , One is datetime modular .
pandas.Timestape
pandas.Timestape Can generate directly pandas Time data
import numpy as np
import pandas as pd
date1 = datetime.datetime(2016,12,1,12,45,30) # Create a datetime.datetime
date2 = '2017-12-21' # Create a string
t1 = pd.Timestamp(date1)
t2 = pd.Timestamp(date2)
print(t1,type(t1))
print(t2,type(t2))
>>>
2016-12-01 12:45:30 <class 'pandas._libs.tslibs.timestamps.Timestamp'> 2017-12-21 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> Copy code
pandas.to_datetime
pandas.to_datetime If it is a single time data , convert to pandas Time data , The data type is Timestamp, If it is multiple time data , Will be converted to pandas Of DatetimeIndex.
Single time data instance :
from datetime import datetime
date1 = datetime(2016,12,1,12,45,30)
date2 = '2017-12-21'
t1 = pd.to_datetime(date1)
t2 = pd.to_datetime(date2)
print(t1,type(t1))
print(t2,type(t2))
>>>
2016-12-01 12:45:30 <class 'pandas._libs.tslibs.timestamps.Timestamp'> 2017-12-21 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'> Copy code
Multiple time data instances :
lst_date = [ '2017-12-21', '2017-12-22', '2017-12-23']
t3 = pd.to_datetime(lst_date)
print(t3,type(t3))
>>>
DatetimeIndex(['2017-12-21', '2017-12-22', '2017-12-23'], dtype='datetime64[ns]', freq=None) <class 'pandas.core.indexes.datetimes.DatetimeIndex'> Copy code
When there are other data formats in multiple time series , We can use error Parameter return ,errors = 'ignore'
: Returns the original input when it is not parsed , Here is the direct generation of general arrays
date3 = ['2017-2-1','2017-2-2','2017-2-3','hello world!','2017-2-5','2017-2-6']
t3 = pd.to_datetime(date3, errors = 'ignore')
print(t3,type(t3))
>>>
['2017-2-1' '2017-2-2' '2017-2-3' 'hello world!' '2017-2-5' '2017-2-6'] <class 'numpy.ndarray'> Copy code
When errors = 'coerce'
when , Data of different data types will be returned NaT, The result is that DatetimeIndex
date3 = ['2017-2-1','2017-2-2','2017-2-3','hello world!','2017-2-5','2017-2-6']
t4 = pd.to_datetime(date3, errors = 'coerce')
print(t4,type(t4))
>>>
DatetimeIndex(['2017-02-01', '2017-02-02', '2017-02-03', 'NaT', '2017-02-05',
'2017-02-06'],
dtype='datetime64[ns]', freq=None) <class 'pandas.core.indexes.datetimes.DatetimeIndex'> Copy code
copyright notice
author[Salted fish Science],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011309371669.html
The sidebar is recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
guess what you like
-
Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
-
Python -- datetime (timedelta class)
-
Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
-
[Python] comparison of dictionary dict, defaultdict and orderdict
-
Test driven development using Django
-
Face recognition practice: face recognition using Python opencv and deep learning
-
leetcode 1610. Maximum Number of Visible Points(python)
-
Python thread 03 thread synchronization
-
Introduction and internal principles of Python's widely used concurrent processing Library Futures
-
Python - progress bar artifact tqdm usage
Random recommended
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)
- Python data analysis - linear regression selection fund
- How to make a python SDK and upload and download private servers
- Python from 0 to 1 (day 20) - basic concepts of Python dictionary
- Django -- closure decorator regular expression
- Implementation of home page and back end of Vue + Django tourism network project
- Easy to use scaffold in Python
- [Python actual combat sharing] I wrote a GIF generation tool, which is really TM simple (Douluo continent, did you see it?)
- [Python] function decorators and common decorators
- Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app
- Construction of the first Django project
- Python crawler actual combat, pyecharts module, python realizes the visualization of river review data
- Python series -- web crawler
- Plotly + pandas + sklearn: shoot the first shot of kaggle
- How to learn Python systematically?
- Analysis on several implementations of Python crawler data De duplication
- leetcode 1616. Split Two Strings to Make Palindrome (python)
- Python Matplotlib drawing violin diagram
- Python crawls a large number of beautiful pictures with 10 lines of code
- [tool] integrated use of firebase push function in Python project
- How to use Python to statistically analyze access logs?