this is what I am doing to get year(1880) from year column(year: 01/01/1880 12:00:00 AM),
import pandas
from datetime import date, datetime, timedelta
data = pandas.read_csv('Landings.csv')
a=data['year']
years = **datetime.datetime.a**
print years
I think the hightlited line is creating probnem anyone correct me, how to get year
I guess data["year"] returns a Series of strings, rather than a string, hence you need to apply/map a parser to to.
import pandas as pd
from datetime import datetime
data = pd.read_csv("Landings.csv")
a=data["year"]
years = [datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]
Alternatively. A more pandas-esque solution (basically, use the pandas.Series.applymethod instead of the list generator). This will leave you in the realm of numpy/pandas
years = data["year"].apply(lambda date: datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year)
Example
In [1]: import pandas as pd
In [2]: from datetime import datetime
In [3]: data = pd.DataFrame({"year": ["01/01/1880 12:00:00 AM"]})
In [4]: data
Out[4]:
year
0 01/01/1880 12:00:00 AM
In [5]: a = data["year"]
In [6]: [datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year for date in a]
Out[6]: [1880]
Since 'a' is a string, it is not a callable function in the datetime module. The following code should work.
import pandas
from datetime import date, datetime, strptime, timedelta
data = pandas.read_csv('Landings.csv')
a=data['year']
years = datetime.strptime(a, '%m/%d/%Y %H:%M:%S %p').year
print years
Related
This question already has answers here:
Convert Pandas Column to DateTime
(8 answers)
Closed 9 months ago.
I have
5/7/2022 12:57(m/d/yyy)
5/7/2022 13:00 PM(m/d/yyy) time formats.
There are two types of time formats in a column of excel file which I have downloaded.
I want to convert it to '%Y-%m-%d %H:%M:%S'.
(The column is in string format).
I guess you have your file loaded from excel to dataframe.
df['date_col'] = pd.to_datetime(df['date_col'], format='%Y-%m-%d %H:%M:%S')
from dateutil.parser import parse
datestring = "5/7/2022 12:57"
dt = parse(datestring)
print(dt.strftime('%Y-%m-%d %H:%M:%S')) #2022-05-07 12:57:00
You can turn string input to datetime by doing this:
from datetime import datetime
example1 = "5/7/2022 12:57"
example2 = "5/7/2022 13:00 PM"
datetime_object1 = datetime.strptime(example1, "%m/%d/%Y %H:%M")
datetime_object2 = datetime.strptime(example2, "%m/%d/%Y %H:%M %p")
and then you can represent the datetime variable with a string:
formatted_datetime1 = datetime_object1.strftime("%Y-%m-%d, %H:%M:%S")
formatted_datetime2 = datetime_object1.strftime("%Y-%m-%d, %H:%M:%S")
You can try using pandas.Series.dt.strftime method, that will allow you to convert a field into the specified date_format, in this case %Y-%m-%d %H:%M:%S.
df['Column'] = df['Column'].dt.strftime('%Y-%m-%d %H:%M:%S')
I'm trying to calculate the beginning of last five fiscal years in Python but it isn't working as expected. What am I missing here?
from datetime import datetime
from dateutil.relativedelta import relativedelta
from fiscalyear import *
a = FiscalYear(datetime.date.today().year)
print(a.start- relativedelta(years=5))
This returns
2015-10-01 00:00:00
while I'm expecting
2016-10-01 00:00:00
Also, how do I test this by passing a future date as parameter? Like, I want to pass 2021-12-22T11:23:48.167 as parameter which should return 20171001 in YYYYmmdd format.
I guess this is what you want as the second part of the question:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from fiscalyear import FiscalYear
FutureDate = datetime.strptime('2030 Jun 1 21:30:00', '%Y %b %d %X')
a = FiscalYear(FutureDate.year)
print(a.start- relativedelta(years = 5))
This question already has answers here:
Python date string to date object
(9 answers)
Closed 1 year ago.
I have a string:
dat="012915"
I want to convert it to a date:
01-29-2015
I tried:
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%Y').date()
dat
but failed:
ValueError: time data '01-29-15' does not match format '%m%d%Y'
%Y is for full year
%y is the short version for year
Your code is totally fine, just change the year directive to lowercase %y will do.
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
dat
I think you are looking for
import datetime
from datetime import datetime
dat="012915"
#lower %y
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)
this will give you
2015-01-29
Trying this out; changing the format string to '%m%d%y' seems to work. Looking at the python docs:
%y Year without century as a zero-padded decimal number.
%Y Year with century as a decimal number.
So the first one is what you need. Source: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
import datetime
from datetime import datetime
dat="012915"
dat = datetime.strptime(dat, '%m%d%y').date()
print(dat)
Change %Y to %y. If you want to use %Y, change dat to '01292015'.
y% is formatted as 15 while %Y is formatted as 2015.
from datetime import datetime
date_str = '012915'
date_obj = datetime.strptime(date_str, '%m/%d/%y')
print("The type of the date is now", type(date_obj))
print("The date is", date_obj)
I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.
This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I have a date stored as a string:-
16/07/2014 13:00:00
I want to convert this into timestamp.
Also from timestamp to this format again.
Please suggest the best possible way to do this in python.
You can use datetime to handle combined dates and times. You could parse this string using datetime.strptime but then you'd have to manually select the formatting.
Alternatively you can use the dateutil package which has a parser which can intelligently guess the string format and return a datetime object, as shown below:
from dateutil import parser
s = '16/07/2014 13:00:00'
d = parser.parse(s)
print(d)
# 2014-07-16 13:00:00
print(type(d))
# datetime.datetime
The documentation to look into this deeper is here
The functions you are looking for are time.strptime(string[, format]) to go from string to timestamp, and then from timestamp to string is time.strftime(format[, t])
Here is an example for your format:
>>> from datetime import datetime
>>>
>>> date_object = datetime.strptime('16/07/2014 13:00:00', '%d/%m/%Y %H:%M:%S')
>>> print date_object
2014-07-16 13:00:00
The to go back to your format (I have used gmtime() to get the current time to show you can convert any datetime to your desired format)
>>> from time import gmtime, strftime
>>> date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
>>> print date_string
17/09/2014 09:31:00
Your best bet is the datetime library: https://docs.python.org/2/library/datetime.html
import datetime
mytime='16/07/2014 13:00:00'
pythontime=datetime.datetime.strptime(mytime, '%d/%m/%Y %H:%M:%S')
stringtime=pythontime.strftime('%d/%m/%Y %H:%M:%S')
Enjoy!