TypeError for datetime - string

This is giving me an Error:
start_date = input('Please Enter the Start Date as Y-M-D H:M:S :- ')
start_time = datetime.strftime(start_date,'%Y-%m-%d %H:%M:%S')
the error:
TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't
apply to a 'str' object
I have imported as follow:
from datetime import datetime,timedelta
Trying to covert imported input string to a start date and time object.

Related

How to convert working with date time in Pandas?

I have datetime field like 2017-01-15T02:41:38.466Z and would like to convert it to %Y-%m-%d format. How can this be achieved in pandas or python?
I tried this
frame['datetime_ordered'] = pd.datetime(frame['datetime_ordered'], format='%Y-%m-%d')
but getting the error
cannot convert the series to <class 'int'>
The following code worked
d_parser= lambda x: pd.datetime.strptime(x,'%Y-%m-%dT%H:%M:%S.%fZ')
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0,parse_dates['datetime_ordered'],date_parser=d_parser)
li.append(df)
frame =pd.concat(li, axis=0, ignore_index=True)
import datetime
from datetime import datetime
date_str="2017-01-15T02:41:38.466Z"
a_date=pd.to_datetime(date_str)
print("date time value", a_date)
#datetime to string with format
print(a_date.strftime('%Y-%m-%d'))

TypeError on Pandas DataFrame

I have an error trying to convert integer numbers to DateTime format on a CSV file using Pandas.
The code I'm using is:
import pandas as pd
from datetime import datetime,timedelta
data=pd.read_csv("Dataset.csv",low_memory=False)
data.Date = data.Date.apply(lambda x:datetime.strptime(x, '%Y-%m-%d'))
The DataFrame is:
The error is:
TypeError: strptime() argument 1 must be str, not int
Does anyone know what is wrong here?
Thank you!!

Converting timeseries into datetime format in python

I have the column of dates called 'Activity_Period' in this format '200507' which means July 2005 and I want to convert it to datetime format of ('Y'-'m') in python.
I tried to use the datetime.strp however it shows that the input has to be a string and not a series.
df.Activity_Period=datetime.strptime(df.Activity_Period, '%Y-%m')
The following is the error I get
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-ac32eb324a0b> in <module>
----> 1 df.Activity_Period=datetime.strptime(df.Activity_Period, '%Y-%m')
TypeError: strptime() argument 1 must be str, not Series
import datetime as dt
import pandas as pd
#simple example
timestamp = '200507'
result = dt.datetime.strptime(timestamp, '%Y%m')
print(result)
#Example using pandas series
series = pd.Series(['200507', '200508', '200509', '200510'])
series = pd.to_datetime(series, format='%Y%m')
print(series)
#for your DF
df['Activity_Period'] = pd.to_datetime(df['Activity_Period'], format='%Y%m')

How to convert a datatype of pandas dataframe from str to float in Python3?

import pandas as pd
d=[('Shubham',24),
('Shrikant',58),
('na',34)]
df = pd.DataFrame(d,columns=['Name','Age'])
df.dtypes
Output:
Name object
Age int32
dtype: object
How do I convert the datatype of 'Name' column to float ?
df['Name'].astype(float)
Getting below error:
ValueError: could not convert string to float: 'na'
If you mean converting the name into number then no, string can't be turn into number directly using astype for what I know. If you meant to encode it then it is as follow:
import pandas as pd
d=[('Shubham',24),
('Shrikant',58),
('na',34)]
df = pd.DataFrame(d,columns=['Name','Age'])
df['Name'] = df['Name'].astype('category').cat.codes
print(df.head())

I am trying to read a .csv file which contains data in the order of timestamp, number plate, vehicle type and exit/entry

I need to store the timestamps in a list for further operations and have written the following code:
import csv
from datetime import datetime
from collections import defaultdict
t = []
columns = defaultdict(list)
fmt = '%Y-%m-%d %H:%M:%S.%f'
with open('log.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
#t = row[1]
for i in range(len(row)):
columns[i].append(row[i])
if (row):
t=list(datetime.strptime(row[0],fmt))
columns = dict(columns)
print (columns)
for i in range(len(row)-1):
print (t)
But I am getting the error :
Traceback (most recent call last):
File "parking.py", line 17, in <module>
t = list(datetime.strptime(row[0],fmt))
TypeError: 'datetime.datetime' object is not iterable
What can I do to store each timestamp in the column in a list?
Edit 1:
Here is the sample log file
2011-06-26 21:27:41.867801,KA03JI908,Bike,Entry
2011-06-26 21:27:42.863209,KA02JK1029,Car,Exit
2011-06-26 21:28:43.165316,KA05K987,Bike,Entry
If you have a csv file than why not use pandas to get what you want.The code for your problem may be something like this.
import Pandas as pd
df=pd.read_csv('log.csv')
timestamp=df[0]
if the first column of csv is of Timestamp than you have an array with having all the entries in the first column in the list known as timestamp.
After this you can convert all the entries of this list into timestamp objects using datetime.datetime.strptime().
Hope this is helpful.
I can't comment for clarifications yet.
Would this code get you the timestamps in a list? If yes, give me a few lines of data from the csv file.
from datetime import datetime
timestamps = []
with open(csv_path, 'r') as readf_obj:
for line in readf_obj:
timestamps.append(line.split(',')[0])
fmt = '%Y-%m-%d %H:%M:%S.%f'
datetimes_timestamps = [datetime.strptime(timestamp_, fmt) for timestamp_ in timestamps]

Resources