SoFunction
Updated on 2024-11-21

Problems with time-date format conversions in python

Every time you encounter pandas dataframe a column date format problems will always be pit, the following record of commonly used time and date function ....

1, string into date str->date

import datetime
date_str = '2006-01-03'
date_ = (date_str,'%Y-&m-%d')

This is the conversion of a single string, where "%Y-%m-%d" represents the format of the date string, if date_str = '2006/1/3', it can be written as "%Y/%m/%d", and so on.

In general, we often manipulate a column of a dataframe:

The apply function can be applied:

def strptime_row(rowi):
  return (rowi,'%Y/%m/%d')
 
df['date'] = df['date'].apply(strptime_row)

may apply () function is a bit less efficient, there should be specialized for a particular column date formatting operations function, such as

import pandas as pd
df['date'] = pd.to_datetime(df['date'])

to_datetime () function can parse a variety of different date representation (such as "7/6/2011", June 7, 2011), the standard date format (such as ISO8601) parsing is very fast.

There is also parse () function, can recognize almost all humans can understand the date representation (but unfortunately not in Chinese), such as:

from  import parse
parse('Jan 31,2008 10:45 AM')

2, the date is converted to a string

You can use the strftime() function

summarize

The above is a small introduction to the python about time and date format conversion problems, I hope to help you, if you have any questions please leave me a message, I will reply to you in time. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!