简体   繁体   English

在 DD/MM/YYYY 和 YYYY-MM-DD 之间转换日期?

[英]Converting date between DD/MM/YYYY and YYYY-MM-DD?

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.使用 Python 脚本,我需要读取日期格式为 DD/MM/YYYY 的 CVS 文件,并将其转换为 YYYY-MM-DD,然后再将其保存到 SQLite 数据库中。

This almost works, but fails because I don't provide time:这几乎可以工作,但因为我没有提供时间而失败:

from datetime import datetime

lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")

#ValueError: time data did not match format:  data=21/12/2008  fmt=%Y-%m-%d
print lastconnection

I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it.我假设 datetime 对象中有一个方法可以很容易地执行此转换,但我找不到如何执行此操作的示例。 Thank you.谢谢你。

Your example code is wrong.您的示例代码是错误的。 This works:这有效:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match.对 strptime() 的调用根据第二个中指定的格式解析第一个参数,因此这两个需要匹配。 Then you can call strftime() to format the result into the desired final format.然后您可以调用 strftime() 将结果格式化为所需的最终格式。

您首先需要将字符串转换为日期时间元组,然后将该日期时间元组转换为字符串,如下所示:

lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')

I am new to programming.我是编程新手。 I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.我想从yyyy-mm-dd转换为dd/mm/yyyy以打印出我所在地区人们使用和认可的格式的日期。

The accepted answer above got me on the right track.上面接受的答案让我走上了正确的轨道。

The answer I ended up with to my problem is:我最终对我的问题的答案是:

import datetime

today_date = datetime.date.today()
print(today_date)

new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)

The first two lines after the import statement gives today's date in the USA format (2017-01-26).导入语句后的前两行以美国格式 (2017-01-26) 给出今天的日期。 The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).最后两行将其转换为英国和其他国家/地区认可的格式 (26/01/2017)。

You can shorten this code, but I left it as is because it is helpful to me as a beginner.您可以缩短此代码,但我保留它是因为它对我作为初学者很有帮助。 I hope this helps other beginner programmers starting out!我希望这对其他初学者程序员有所帮助!

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation?有没有其他人认为将这些字符串转换为日期/时间对象是一种浪费,最终是一个简单的文本转换? If you're certain the incoming dates will be valid, you can just use:如果您确定传入的日期是有效的,您可以使用:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.这几乎肯定会比日期转换更快。

If you need to convert an entire column (from pandas DataFrame ), first convert it ( pandas Series ) to the datetime format using to_datetime and then use .dt.strftime :如果您需要转换整个列(来自pandas DataFrame ),首先使用.dt.strftime将其( pandas Series )转换为datetime时间格式,然后使用to_datetime

def conv_dates_series(df, col, old_date_format, new_date_format):

    df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
    
    return df

Sample usage:示例用法:
import pandas as pd

test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})

old_date_format='%Y-%m-%d'
new_date_format='%d/%m/%Y'

conv_dates_series(test_df, "Dates", old_date_format, new_date_format)

    Dates
0   01/01/1900
1   31/12/1999

#case_date= 03/31/2020   

#Above is the value stored in case_date in format(mm/dd/yyyy )

demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it 
print(new_case_date)

The most simplest way最简单的方法

While reading the csv file, put an argument parse_dates在读取 csv 文件时,输入参数parse_dates

df = pd.read_csv("sample.csv", parse_dates=['column_name'])

This will convert the dates of mentioned column to YYYY-MM-DD format这会将提到的列的日期转换为 YYYY-MM-DD 格式

Convert date format DD/MM/YYYY to YYYY-MM-DD according to your question, you can use this:根据您的问题将日期格式 DD/MM/YYYY 转换为 YYYY-MM-DD,您可以使用这个:

from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
print(lastconnection)
  • df is your data frame df是您的数据框
  • Dateclm is the column that you want to change Dateclm是您要更改的列

This column should be in DateTime datatype.此列应为DateTime数据类型。

df['Dateclm'] = pd.to_datetime(df['Dateclm'])

df.dtypes


#Here is the solution to change the format of the column

df["Dateclm"] = pd.to_datetime(df["Dateclm"]).dt.strftime('%Y-%m-%d')

print(df)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM