[英]Extract Date from excel and append it in a list using python
I have an column in excel which has dates in the format ''17-12-2015 19:35". How can I extract the first 2 digits as integers and append it to a list? In this case I need to extract 17 and append it to a list. Can it be done using pandas also? 我在excel中有一列,其日期格式为“ 17-12-2015 19:35”。如何将前两位数字提取为整数并将其附加到列表中?在这种情况下,我需要提取17和将其添加到列表中,也可以使用熊猫吗?
Code thus far: 到目前为止的代码:
import pandas as pd
Location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(Location)
time = df['Creation Date'].tolist()
print (time)
You could extract the day of each timestamp like 您可以提取每个时间戳记的日期,例如
from datetime import datetime
import pandas as pd
location = r'F:\Analytics Materials\files\paymenttransactions.csv'
df = pd.read_csv(location)
timestamps = df['Creation Date'].tolist()
dates = [datetime.strptime(timestamp, '%d-%m-%Y %H:%M') for timestamp in timestamps]
days = [date.strftime('%d') for date in dates]
print(days)
The '%d-%m-%Y %H:%M'
and '%d'
bits are format specififers, that describe how your timestamp is formatted. '%d-%m-%Y %H:%M'
和'%d'
位是格式说明符,用于描述时间戳的格式。 See eg here for a complete list of directives. 请参阅此处的指令完整列表。
datetime.strptime
parses a string into a datetime
object using such a specifier. datetime.strptime
使用这样的说明符将字符串解析为datetime
对象。 dates
will thus hold a list of datetime
instances instead of strings. dates
将因此包含datetime
实例列表,而不是字符串。
datetime.strftime
does the opposite: It turns a datetime
object into string, again using a format specifier. datetime.strftime
作用与此相反:再次使用格式说明符将datetime
对象转换为字符串。 %d
simply instructs strftime
to only output the day of a date. %d
仅指示strftime
仅输出日期中的日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.