How to convert string in to date in Python [duplicate] - python

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)

Related

How do I convert date and time string(1975-07-14T16:32:47.000Z) to Day-Month name-Year (14 July 1975) format in python [duplicate]

This question already has answers here:
How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]
(11 answers)
Closed 4 months ago.
I am writing a UI automated test that checks a date in the database and returns the date as a string in this format 1975-07-14T16:32:47.000Z and comparing it to the date that is displayed on the webpage but the date on the webpage is in this format Day-Month name-Year (14 July 1975), therefore I need to convert the date return by the database to Day-Month name-Year (14 July 1975) so that I am comparing like for like. How do I change the date string to the format I need
You can use dateutil.parser to parse the string you got from the datebase into a datetime.datetime, which in turn can be formatted using strftime:
import dateutil.parser
input="1975-07-14T16:32:47.000Z"
dt = dateutil.parser.parse(input)
print(dt.strftime("%d %B %Y"))
from datetime import datetime
dt_string = "1975-07-14T16:32:47.000Z"
datetime_object = datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S.%fZ")
new_datetime_string = datetime.strftime(datetime_object, "%d-%B-%Y")
print(new_datetime_string)
# prints "14-July-1975"
We are using datetime module where datetime.strptime will generate a datetime object where you can call .date(),.time(),.today() and other functions but to get back to string as per the given format of Day-Month Name-Year datetime.strftime()(stringify time) is used. This converts datetime obj to given format of datetime string.
%d - date (DD - 01,02,...,31)
%m - month (MM - 01,02,...,12)
%Y - Year (YYYY - 2022,2021,...)
%B - Full Month Name (January, Feburary,..)
%f - Milliseconds
you can find out more in following link: Datetime format codes

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

Pandas dataframe to_datetime() is converting date incorrectly

I have a date in this format - '17-JUL-53'
when I pd.to_datetime('17-JUL-53') it returns Timestamp('2053-07-17 00:00:00')
You could say it is correct, but the actual date to be returned is 1953-07-17. That comes out OK in excel, how do we do that with to_datetime()?
[edit] Just to show what happens when we convert from str to time in python:
>>> time.strptime('17-JUL-53', '%d-%b-%y')
time.struct_time(tm_year=2053, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0,tm_sec=0, tm_wday=3, tm_yday=198, tm_isdst=-1)
I think you need add substring 19 to year.
More info about formatting of datetime is here.
import pandas as pd
s = '17-JUL-53'
d = s[:7] + '19' + s[7:]
print d
#17-JUL-1953
dt = pd.to_datetime(d, format='%d-%b-%Y')
print dt
#1953-07-17 00:00:00
%d-%b-%Y means:
%d - Day of the month as a zero-padded decimal number
%b - Month as locale’s abbreviated name
%Y - Year with century as a decimal number
I would do it this way, providing all your dates are in the 1900 century :)
from dateutil.relativedelta import relativedelta
input ='17-jul-53'
output = pd.to_datetime(input)
output_clean = output - relativedelta(years=100)
Somehow you need to mention in which century you are ... in pandas this cannot be handled by to_datetime function, so you need to do it upstream. Here is an approach with regex:
import re
import pandas as pd
date = '17-JUL-53'
pd.to_datetime(re.sub(r'(\d{2}-\w{3}-)(\d{2})', r'\g<1>19\2', date))
#Timestamp('1953-07-17 00:00:00')

Change Date Format In Python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I need to convert date string "Dec 17 00:00:06" to string "2014-12-17 00:00:06" in python. I looked at the datetime.strptime but still can't find a way for this.
eg:
Dec 17 00:00:06 to 2014-12-17 00:00:06
You can use datetime module.
For e.g.
>>> import datetime
>>> do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
We can replace year value to 2014 like following:
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'1900-12-17 00:00:06'
>>> do1 = do.replace(year=2014)
>>> do1.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
If we want only time value then we can try like-
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%H:%M:%S")
'00:00:06'
Updated: update datetime string from file with its time string.
Algo:
Get content from the input text file.
Used re module i.e regular expression to get all pattern from content.
Use set method to remove duplicate values.
Convert datetime string to time string and update content.
Write new content into same file or other file.
code is:-
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
content = fp.read()
date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )
p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
fp.write(content)
Using datetime module will help you out.
from datetime import datetime
Firstly convert your date string to a datetime object by writing the line below.
date_obj = datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
Then convert that date object to a string.
date_obj.strftime("%Y-%m-%d %H:%M:%S")
You can change the parameters of the above strftime() function, and get different formats as per your requirments. Please follow python datetime
Here is the link to the options for the parameters which can be passed in the strftime() function parameter options
Go and play around as per your requirement.
from dateutil import parser
parser.parse('Dec 17 00:00:06').isoformat()
>>> '2015-12-17T00:00:06'

Convert string datetime to timestamp and vice verse in python [duplicate]

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!

Categories

Resources