[Python] How to change character string (str) data to date (strptime of datetime)

[For beginners] How to change python string (str) data to date (datetime strptime)

The date data scraped on the WEB is a character string (str).

Convert the character string to date in order to store the acquired data in DB as date data.

manner

Use the strptime method of the datetime module.


## import datetime module If you define the notation omitted in import datetime as dt, it will be easier to use later.

python


import datetime as dt

** Differences in usage with and without abbreviated definition **

No definition


import datetime

datetime.datetime.now()
#It is necessary to describe the module name at the beginning in full

With definition


import datetime

dt.datetime.now()
#The module name at the beginning can be abbreviated

## Change the date of the string to a datetime type date ** strptime method ** -Convert character strings to date data `datetime.datetime.strptime('A','B')` └ datetime.datetime.strptime () is one set └ A: Character string (str) └ B: Format

** How to use strptime ('A','B') ** -Match "A character string" and "B format".

Example 1(0 not filled)


A:「2019-1-9」
B:「%Y-%m-%d」

dt.datetime.strptime('2019-1-9','%y-%m-%d')

#output
datetime.datetime(2019, 1, 9, 0, 0)

% Y: 4 digits in the Christian era % m: Month (character string month is padded with 0 or not) % d: Day (character string month is padded with 0 or not)


Example 2(0 padded)


A:「19-05-08」
B:「%y-%m-%d」

dt.datetime.strptime('19-05-08','%y-%m-%d')

#output
datetime.datetime(2019, 5, 8, 0, 0)

% y: 2 digits (lowercase) % m,% d: 0 Supports both with and without padding


Example 3(date)


A: "May 8, 2019"
B:「%Y year%m month%d day "

dt.datetime.strptime('May 8, 2019','%Y year%m month%d day')

#output
datetime.datetime(2019, 5, 8, 0, 0)

Example 4(Correspondence between character strings and numerical values)


A: "Tomorrow's date is May 8th. The year is 2019."
B: "Tomorrow's date is%m month%d days. Year is%Y year "

dt.datetime.strptime('Tomorrow's date is May 8th. Year is 2019','Tomorrow's date%m month%d days. Year is%Y year')

#output
datetime.datetime(2019, 5, 8, 0, 0)

・ Dates are not in order -Just specify which number will be the date data


Example 5(variable)


A:「past」:'2019/3/23'
B:「%Y/%m/%d」

past= '2019/3/23'
dt.datetime.strptime(past,'%Y/%m/%d')

#output
datetime.datetime(2019, 3, 23, 0, 0)

Error when quoting variables ValueError: time data 'past' does not match format '%Y/%m/%d'


Example 6(Time,Minutes,Including seconds)


A:「future」:'March 23, 2030 5:21:42 123456 microseconds'
B:「%Y year%m month%d day%H o'clock%M minutes%S seconds%f microseconds "

past= '2019/3/23'
dt.datetime.strptime(future, '%Y year%m month%d day%H o'clock%M minutes%S seconds%f microseconds')

#output
datetime.datetime(2030, 3, 23, 5, 21, 42, 123456)

% H: Time (24-hour notation) % M: minutes % S: seconds % f: microseconds



## Supplement ### Example of how to use the datetime module ** Find the current time (now method) ** `datetime.datetime.now()`    ** Code meaning ** (1) Find the current time by "(3) now method" in (2) "datetime type (year, month, day, hour, minute, second, microsecond)" of "datetime module".

code


dt.datetime.now()

#output
# datetime.datetime(2020, 3, 23, 0, 18, 1, 735003)

### Why does [datetime] continue twice? When I try it for the first time, is it tedious and necessary that datetime continues twice in a row at the beginning like "datetime.datetime.now ()"? It was an impression.

The meaning of each

In the first place, it was a mistake to think that "datetime.datetime.now ()" was divided into three parts, "①datetime", "②.datetime", and "③now ()".

Correctly, it is divided into two parts, "(1) datetime.datetime" and "(2) now ()".

Objects and methods

The syntax for using the method is object . method, so it looks like this:

Object: ① datetime.datetime Method: ② now ()

object

Put an entity in the object.

** ** -Substituted variable (eg a = 3) -Instance (materialized class)

→ datetime.datetime is an instance

Datetime instance (class) type

It's hard to understand if you just look at "datetime.datetime", but there are other types.

datetime.date: date datetime.time: time datetime.timedelta: difference datetime.tzinfo: Time zone information

Such

What is being done

▶「datetime.datetime.now()」 datetime.datetime is a collection of functions related to" date and time ". The now () method calls the now () function defined in datetime.datetime.

▶「datetime.date.now()」 ** Error **. datetime.date is a collection of functions related to" time ". The function now () is not defined in this.

▶「datetime.time.today()」 You can use this. A function called today () is defined in the class of datetime.date.

Summary

--Multiple classes are defined in the datetime module. --Specify the class with the data you want to handle (date, time, both? Etc.) --Class (instance) specification: datetime.AAAA --The methods defined for each class are different. --Use the method that suits each class: datetime.AAAA.BBBB ()

datetime.time.today() datetime.datetime.today()

Recommended Posts

[Python] How to change character string (str) data to date (strptime of datetime)
Conversion of string <-> date (date, datetime) in Python
[Python] How to invert a character string
Convert "number" of excel date to python datetime
[Python] How to change the date format (display format)
[Python] How to expand variables in a character string
python> datetime> From date string (ISO format: 2015-12-09 12:40:08) to datetime type
How to change Python version
[Python] How to make a list of character strings character by character
Python learning basics ~ How to output (display) a character string? ~
How to change python version of Notebook in Watson Studio (or Cloud Pak for Data)
How to quickly count the frequency of appearance of characters from a character string in Python?
How to calculate date with python
How to change the log level of Azure SDK for Python
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to output a character string in a Print statement
How to avoid duplication of data when inputting from Python to SQLite.
[Python] Summary of how to use pandas
[Python2.7] Summary of how to use unittest
Basic grammar of Python3 system (character string)
How to use "deque" for Python data
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
[Introduction to Data Scientists] Basics of Python ♬
[Question] How to use plot_surface of python
How to send a visualization image of data created in Python to Typetalk
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] Thorough explanation of the character string type used in Python!
[Python --open3d] How to convert obj data of 3D model to point cloud
Summary of how to read numerical data with python [CSV, NetCDF, Fortran binary]
Summary of how to import files in Python 3
Python datetime How to calculate dates and convert strings strftime, strptime [Definitive Edition]
[Python] How to read data from CIFAR-10 and CIFAR-100
Summary of how to use MNIST in Python
[Introduction to Python] How to handle JSON format data
How to specify attributes with Mock of python
Calculation of match rate of character string breaks [python]
How to get dictionary type elements of Python 2.7
How to handle datetime type in python sqlite3
[Python] How to compare datetime with timezone added
[Introduction to Python] How to get the index of data with a for statement
[Python] Summary of eval / exec functions + How to write character strings with line breaks
How to convert / restore a string with [] in python
Summary of tools needed to analyze data in Python
How to convert Python # type for Python super beginners: str
How to get the number of digits in Python
I tried to summarize how to use matplotlib of python
How to write string concatenation in multiple lines in Python
[For beginners] How to study Python3 data analysis exam
How to scrape image data from flickr with python
Change IP settings to ACL of conoha with python
Store Japanese (multibyte character string) in sqlite3 of python
How to write a list / dictionary type of Python3
How to use Python Kivy ① ~ Basics of Kv Language ~
[Python] Summary of how to specify the color of the figure
[Work efficiency] How to change file names in Python
Summary of date processing in Python (datetime and dateutil)
I tried to summarize the string operations of Python
How to install Python
How to install python
[Python2] Date string-> UnixTime-> Date string