format 01-01-16 7:43 string to datetime - python

I have the following strings that I'd like to convert to datetime objects:
'01-01-16 7:43'
'01-01-16 3:24'
However, when I try to use strptime it always results in a does not match format error.
Pandas to_datetime function nicely handles the automatic conversion, but I'd like to solve it with the datetime library as well.
format_ = '%m-%d-%Y %H:%M'
my_date = datetime.strptime("01-01-16 4:51", format_)
ValueError: time data '01-01-16 4:51' does not match format '%m-%d-%Y %H:%M'

as i see your date time string '01-01-16 7:43'
its a 2-digit year not 4-digit year
that in order to parse through a 2-digit year, e.g. '16' rather than '2016', a %y is required instead of a %Y.
you can do that like this
from datetime import datetime
datetime_str = '01-01-16 7:43'
datetime_object = datetime.strptime(datetime_str, '%m-%d-%y %H:%M')
print(type(datetime_object))
print(datetime_object)
give you output 2016-01-01 07:43:00

First of all, if you want to match 2016 you should write %Y while for 16 you should write %y.
That means you should write:
format_ = '%m-%d-%y %H:%M'
Check this link for all format codes.

Related

Finding the right format for pd.to_datetime

I'm trying to convert strings in my dataset('2016-01-01 00:00:00') to time stamps using pd.to_datetime.
Im trying:
pd.to_datetime(train["timestamp"],format='%Y/%m/%d %I:%M:%S')
but I get
time data '2016-01-01 00:00:00' does not match format '%Y/%m/%d %I:%M:%S' (match)
How can I fix this?
If you want it to be in the specific format that you mentioned, that is %Y/%m/%d %I:%M:%S, then do it like this.
First convert your string to datetime format using to_datetime:
df['timestamp'] = pd.to_datetime(df['timestamp'])
Now that your column is in datetime format, convert to the following format using strftime:
df['timestamp'] = df['timestamp'].dt.strftime('%Y/%m/%d %I:%M:%S')
Output:
timestamp
0 2016/01/01 12:00:00
1 2016/01/01 12:00:00
As others pointed out, use %H instead of %I for 24 hour format, like this:
df['timestamp'] = df['timestamp'].dt.strftime('%Y/%m/%d %H:%M:%S')
That's because your format in your df is different. Try the following using -, also use %H for 24-hour clock:
pd.to_datetime(train["timestamp"],format='%Y-%m-%d %H:%M:%S')
2 issues here:
Use - instead of /
%I is for Hour 00-12, use %H for Hour 00-23
pd.to_datetime(train["timestamp"],format='%Y-%m-%d %H:%M:%S')

Python: convert datetime format to another

So i have this kind f format:
'%Y-%m-%d %H:%M:%S.%f'
date_time = datetime.now()
Ouput
'2019-04-15 07:52:14.211697'
And i want to change is into this format: '%Y-%m-%d %H:%M:%S,%f'
This is what i have try:
time = datetime.strptime(str(date_time), '%Y-%m-%d %H:%M:%S,%f')
And this is the error:
ValueError: time data '2019-04-15 07:52:14.211697' does not match
format '%Y-%m-%d %H:%M:%S,%f'
Edit
So i have this string:
maches = regex.findall(
'[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1]) (?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9],[0-9][0-9][0-9]',
line)
match[0] = '2019-03-13 17:35:35,855'
And i want to convert it to Datetime:
time = datetime.strptime(maches[0], '%Y-%m-%d %H:%M:%S,%f')
And this returned another format:
2019-03-13 17:35:35.855000
Why ?
You want to use strftime:
str_time = datetime.strftime(date_time, '%Y-%m-%d %H:%M:%S,%f')
A quick comparison of strftime and strptime:
strftime() is used to convert a datetime object to a string
strptime() is used to convert a date string to a datetime object
Also here's a good resource in the documentation describing the differences: strftime() and strptime() Behavior
Response to Question Edit
In response to your edit strptime takes a string date and converts it into a datetime object. The format you pass to it just tells it how to parse the string to datetime. It does not dictate it's print format. You are calling print on a datetime object in this case so the output is dictated by the __str__ method on the datetime object.
If you want to print it in a certain way pass it to strftime with the format you want to output it as:
obj_time = datetime.strptime(maches[0], '%Y-%m-%d %H:%M:%S,%f')
print(datetime.strftime(obj_time , '%Y-%m-%d %H:%M:%S,%f'))
Use strftime.
date_time = datetime.now()
print(date_time)
print(datetime.strftime(date_time, '%Y-%m-%d %H:%M:%S,%f'))
2019-04-15 10:26:08.637630
2019-04-15 10:26:08,637630
Use this you get this format '%Y-%m-%d %H:%M:%S,%f'
print '{:%Y-%m-%d %H:%M:%S.%f}'.format(date_time)

How can I convert text to DateTime?

I scraped a website and got the following Output:
2018-06-07T12:22:00+0200
2018-06-07T12:53:00+0200
2018-06-07T13:22:00+0200
Is there a way I can take the first one and convert it into a DateTime value?
Just parse the string into year, month, day, hour and minute integers and then create a new date time object with those variables.
Check out the datetime docs
You can convert string format of datetime to datetime object like this using strptime, here %z is the time zone :
import datetime
dt = "2018-06-07T12:22:00+0200"
ndt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S%z")
# output
2018-06-07 12:22:00+02:00
The following function (not mine) should help you with what you want:
df['date_column'] = pd.to_datetime(df['date_column'], format = '%d/%m/%Y %H:%M').dt.strftime('%Y%V')
You can mess around with the keys next to the % symbols to achieve what you want. You may, however, need to do some light cleaning of your values before you can use them with this function, i.e. replacing 2018-06-07T12:22:00+0200 with 2018-06-07 12:22.
You can use datetime lib.
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.strptime documentation
Solution here

Python change a date format in dataframe

I have a dataset containing a column "date":
date item
20.3.2010 17:08 a
20.3.2010 11:16 b
2010-03-20 15:55:14.060 c
2010-03-21 13:56:45.077 d
I would like to convert all values that have format as 20.3.2010 17:08 into 2010-03-21 13:56:45.077.
Does anybody have an idea?
Thank you.
Check on below:
from datetime import datetime
INPUT_FORMAT = '%d.%m.%Y %H:%M'
OUTPUT_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
datetime.strptime('20.3.2010 17:08',INPUT_FORMAT).strftime(OUTPUT_FORMAT)
#Output '2010-03-20 17:08:00.000000'
You could find more information in offcial strptime and strftime.
To do a 100% match with 3 digits microseconds you could use this SO approach.
df['date'] = pd.to_datetime(df['date'], , format = '%Y-%m-%d %H:%M:%S.%f')
You can find more information on pd.to_datetime() here, and the format string type can be found here.

Converting string to date that contains 00:00:00

To convert a string date to date format dropping the '00:00:00' I use :
import datetime
strDate = '2017-04-17 00:00:00'
datetime.datetime.strptime(strDate, '%Y/%m/%d %H:%M:%S').strftime('%Y-%m-%d')
Returns :
ValueError: time data '2017-04-17 00:00:00' does not match format '%Y/%m/%d %H:%M:%S'
Is %H:%M:%S not correct format ?
This is the correct way:
datetime.datetime.strptime(strDate, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
Notice the - instead of / in strptime. The date is converted to: 2017-04-17.
If you would like to have it displayed a different way, have a look here.

Categories