2018-02-06T14:45:03.0040554Z
Unable to convert this string to datetime.
datetime.strptime('2018-02-06T14:45:03.0040554Z', '%Y-%m-%dT%H:%M:%fZ')
I am trying this and it doesn't work.
datetime.strptime('2018-02-06T14:45:03Z', '%Y-%m-%dT%H:%M:%fZ')
This work for above time format.
But I'm getting this time string from third party api so can't change its format.
If you can use the dateutil module you can do this.
from dateutil import parser
print parser.parse('2018-02-06T14:45:03.0040554Z')
Output:
2018-02-06 14:45:03.004055+00:00
Using Datetime. Looks like you missed the seconds param and the microseconds need to be 6 you have 7.
import datetime
print datetime.datetime.strptime('2018-02-06T14:45:03.004055Z', '%Y-%m-%dT%H:%M:%S.%fZ')
print datetime.datetime.strptime('2018-02-06T14:45:03Z', '%Y-%m-%dT%H:%M:%SZ')
Output:
2018-02-06 14:45:03.004055
2018-02-06 14:45:03
One way is to use pandas:
import pandas as pd
pd.to_datetime('2018-02-06T14:45:03.0040554Z').to_pydatetime()
'2018-02-06 14:45:03.004055'
Your input format is super-strange, as it has 7 digits in second fraction
Take a look at old question: How do I convert a date string containing 7 digits in milliseconds into a date in Python
You can either split/rejoin string and use '%Y-%m-%dT%H:%M:%S.%fZ' or use dateutil.parser.parse
Related
I have a string in dd-MON-yy format. While converting to date in python, its is causing issue since the year is in tow digits.
datetime.datetime.strptime('17-JUN-03', '%d-%m-%y')
The error is,
ValueError: time data '17-JUN-03' does not match format '%d-%m-%y'
Try this:
import datetime
print(datetime.datetime.strptime('17-JUN-03', '%d-%b-%y'))
Result:
2003-06-17 00:00:00
Datetime format codes
I have following datetime in Python and want to convert it to numeric
2020-04-01 12:30:01
When I convert this to number in excel it returns 43922.5208449074. How to get the same number in Python?
I tried with following
datetime.fromisoformat('2020-04-01 12:30:01').timestamp()
But it does not return me the same number. How can we do it in Python
If i am understanding your problem,
you can use it
# Importing datetime.
from datetime import datetime
# Creating a datetime object so we can test.
a = datetime.now()
# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))
print (a)
I want to generate time/date format strings from the input data I got.
Is there an easy way to do this?
My input data looks like this:
'01.12.2016 23:30:59,123'
So my code should generate the following format string:
'%d.%m.%Y %H:%M:%S,%f'
Background:
I used pandas.to_datetime() to generate datetime object for further processing. This works great but this function gets slow (uses dateutil.parser.parse here) with a lot of data (>~50k). At the moment I'm providing the format string above hardcoded within my code to speed up to_datetime() which also works great. Now I wanted to generate the format string within code to be more flexible regaring the input data.
edit (because the first two answers do not fit to my question):
I want to generate the format string not the datetime string.
edit2:
New approch to formulate the question: I'm reading in a file with a lot of data. Every line of data has got a timestamp with the following format: '01.12.2016 23:30:59,123'. I want to convert these timestamps into datetime objects. For this I'm using pandas.to_datetime() at the moment. This function works perfectly but it get slow since I got some files with over 50k datasets. To speed this process up I'm passing a format string within the function pandas.to_datetime(format='%d.%m.%Y %H:%M:%S,%f'). This speeds up the process but it is less flexible. Therefore I want to evaluate the format string only for the first dataset and use it for the rest of the 50k or more datasets.
How is this possible?
you can try to use infer_datetime_format parameter, but be aware - pd.to_datetime() will use dayfirst=False per default
Demo:
In [422]: s
Out[422]:
0 01.12.2016 23:30:59,123
1 23.12.2016 03:30:59,123
2 31.12.2016 13:30:59,123
dtype: object
In [423]: pd.to_datetime(s, infer_datetime_format=True)
Out[423]:
0 2016-01-12 23:30:59.123
1 2016-12-23 03:30:59.123
2 2016-12-31 13:30:59.123
dtype: datetime64[ns]
In [424]: pd.to_datetime(s, infer_datetime_format=True, dayfirst=True)
Out[424]:
0 2016-12-01 23:30:59.123
1 2016-12-23 03:30:59.123
2 2016-12-31 13:30:59.123
dtype: datetime64[ns]
use "datatime" to return the data and time. I this this will help you.
import datetime
print datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S,%f')
You can use datetime.strptime() inside datetime package which would return a datetime.datetime object.
In your case you should do something like:
datetime.strptime('01.12.2016 23:30:59,123', '%d.%m.%Y %H:%M:%S,%f').
After you have the datetime.datetime object, you can use datetime.strftime() function to get the datetime in the desired string format.
You should probably have a look here: https://github.com/humangeo/DateSense/
From its documentation:
>>> import DateSense
>>> print DateSense.detect_format( ["15 Dec 2014", "9 Jan 2015"] )
%d %b %Y
I have a variable 'd' that contains dates in this format:
2015-08-03T09:00:00-07:00
2015-08-03T10:00:00-07:00
2015-08-03T11:00:00-07:00
2015-08-03T12:00:00-07:00
2015-08-03T13:00:00-07:00
2015-08-03T14:00:00-07:00
etc.
I need to strip these dates, but I'm having trouble because of the timezone. If I use d = dt.datetime.strptime(d[:19],'%Y-%m-%dT%H:%M:%S'), only the first 19 characters will appear and the rest of the dates are ignored. If I try d = dt.datetime.strptime(d[:-6],'%Y-%m-%dT%H:%M:%S, Python doesn't chop off the timezone and I still get the error ValueError: unconverted data remains: -07:00. I don't think I can use the dateutil parser because I've only seen it be used for one date instead of a whole list like I have. What can I do? Thanks!
Since you have a list just iterate over and use dateutil.parser:
d = ["2015-08-03T09:00:00-07:00","2015-08-03T10:00:00-07:00","2015-08-03T11:00:00-07:00","2015-08-03T12:00:00-07:00",
"2015-08-03T13:00:00-07:00","2015-08-03T14:00:00-07:00"]
from dateutil import parser
for dte in d:
print(parser.parse(dte))
If for some reason you actually want to ignore the timezone you can use rsplit with datetime.strptime:
from datetime import datetime
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S"))
If you had a single string delimited by commas then just use d.split(",")
You can use strftime to format the string in any format you want if you actually want a string:
for dte in d:
print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"))
How can I calculate the next day from a string like 20110531 in the same YYYYMMDD format? In this particular case, I like to have 20110601 as the result. Calculating "tomorrow" or next day in static way is not that tough, like this:
>>> from datetime import date, timedelta
>>> (date.today() + timedelta(1)).strftime('%Y%m%d')
'20110512'
>>>
>>> (date(2011,05,31) + timedelta(1)).strftime('%Y%m%d')
'20110601'
But how can I use a string like dt = "20110531" to get the same result as above?
Here is an example of how to do it:
import time
from datetime import date, timedelta
t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')
>>> from datetime import datetime
>>> print datetime.strptime('20110531', '%Y%m%d')
2011-05-31 00:00:00
And then do math on that date object as you show in your question.
The datetime library docs.
You are most of the way there! along with the strftime function which converts a date to a formatted string, there is also a strptime function which converts back the other way.
To solve your problem you can just replace date.today() with strptime(yourDateString, '%Y%m%d').
ED: and of course you will also have to add strptime to the end of your from datetime import line.