How do I convert string date to datetime? - python

The dates that I have in a data frame are formatted like this:
Apr 5, 2010.
How can I convert them to datetime?
Here's what I've tried so far:
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.datetime.strptime(date_time_str, '%m %d, %Y')
print(date_time_obj)
But I know this is wrong.
(I've tried looking for similar questions on here, but most people have their string dates formatted like 05-05-2010.)

The following code will produce a new datetime object with the values you would like.
from datetime import datetime
date_time_str = 'Sep 28, 2019'
date_time_obj = datetime.strptime(date_time_str, '%b %d, %Y')
print(date_time_obj)
print(type(date_time_obj)) # verify object type

Related

How can I change this format to be datetime format? (python)

I have a dataset which contains some columns with datetime. My problem is, I found this type datetime format:
Apr'11
Apr-11
Apr 11
How can I automatically change this format to be datetime format?
for you can use datetime module
from datetime import datetime
this is the link if you want any confusion
date_string = "Apr'11"
date = datetime.strptime(date_string, "%b'%d")
%b = Locale’s abbreviated month name. (like Apr, Mar, Jan, etc)
%d = Day of the month as a decimal number [01,31]
date_string_2 = "Apr-11"
date = datetime.strptime(date_string, "%b-%d")
date_string_3 = "Apr 11"
date = datetime.strptime(date_string, "%b %d")
You should write this "%b %d" same as like date_string otherwise it will give you, even if you give an extra space.
go to this link to learn more about this:
https://docs.python.org/3/library/time.html

how to convert date to mysql format in python

How to convert date to mysql date format like Dec 21, 2019 to 2019-12-21 in python.
Please help, I am new to python.
i tried date.strftime("%Y-%m-%d %H:%M:%S") but its won't work.
You need to provide the correct format string.
import datetime
d = datetime.datetime.strptime("Dec 21, 2019","%b %d, %Y")
d.strftime("%Y-%m-%d")
If you're not sure about the format of date and/or expecting multiple formats, you can use the below code snippet
from dateutil.parser import parse
d = parse("Dec 21, 2019")
d.strftime("%Y-%m-%d")
Example snippet for date conversion.
from datetime import datetime
oldformat = 'Dec 21, 2019'
datetimeobject = datetime.strptime(oldformat,'%b %d, %Y')
newformat = datetimeobject.strftime('%Y-%m-%d')
print(newformat)

Convert string to DateTime for mysql in python

I want to convert my date into DateTime object for MySQL.
My string format is: Mon Aug 27 04:47:45 +0000 2018
Expected Output: 'YYYY-M-D H:mm:ss'
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S % z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')
Refer section 8.1.8
here
If you are using python 3, this solution would work -
from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'
But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here
Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')
You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:
query = "select * from table where date >" + str(date_as_dt_object)
Check out this list for Python's strftime directives.
http://strftime.org/

get hours from full date date to python3

I work with api in python3 in this api return date like this
'Jun 29, 2018 12:44:14 AM'
but i need just hours, minute ad second like this
12:44:14
are there a fonction that can format this
It looks like the output is a string. So, you can use string slicing:
x = 'Jun 29, 2018 12:44:18 AM'
time = x[-11:-3]
It's best to use negative indexing here because the day may be single-digit or double-digit, so a solution like time = x[13:21] won't work every time.
If you're inclined, you may wish to use strptime() and strftime() to take your string, convert it into a datetime object, and then convert that into a string in HH:MM:SS format. (You may wish to consult the datetime module documentation for this approach).
Use the datetime module. Use .strptime() to convert string to datetime object and then .strftime() to convert to your required string output. Your sample datetime string is represented as '%b %d, %Y %H:%M:%S %p'
Ex:
import datetime
s = 'Jun 29, 2018 12:44:14 AM'
print( datetime.datetime.strptime(s, '%b %d, %Y %H:%M:%S %p').strftime("%H:%M:%S") )
Output:
12:44:14

Converting date in python

I need to convert dates that look like this "2/28/2012" into Feb 28, 2012.
Anyone know how to do this using string slicing, split, and datetime?
Just using datetime.datetime:
from datetime import datetime
date_str = '2/28/2014'
new_date_str = datetime.strptime(date_str, '%m/%d/%Y').strftime('%b %d, %Y')
>>> print new_date_str
Feb 28, 2014
strptime() parses the date string into a datetime.datetime object. strftime() converts that datetime back to a string in the required format.
If you want to do it with string operations:
months = {'1': 'Jan', '2': 'Feb', '3': 'Mar', ...., '12': 'Dec'}
date_str = '2/28/2014'
month, day, year = date_str.split('/')
new_date_str = '{} {}, {}'.format(months[month], day, year)
Yes you can. Try something like this...
from calendar import month_abbr
dateNonFormat = "2/28/2012"
splitDate = dateNonFormat.split("/")
monthFormatted = month_abbr[int(splitDate[0])]
formattedDate = "%s %s, %s" % (monthFormatted, s[1], s[2])
In this example your formatted date would be Feb 28, 2012
You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.string_to_string('2/28/2012', '%m/%d/%Y', '%b %d, %Y')

Categories

Resources