Convert a series of string to date [duplicate] - python

This question already has answers here:
How to change the datetime format in Pandas
(8 answers)
Closed 4 years ago.
I have the data like this
df['Date']=['05.01.2017','05.01.2017']
I tried
df1= pd.to_datetime(df['Date'])
but it turned a bad result
Id like to get the new data like this
result=[05-01-2017,05-01-2017]

You just need to specify the format of the dates in your column. This works for me from your example. Simple.
pd.to_datetime(df['Date'], format = '%d.%m.%Y')
I'm assuming that the numbers in your dates are day.month.year respectively and not month.day.year. If the latter is true then you should use format = '%m.%d.%Y' instead.

If you know your dates are always going to be strings in the form of MM.DD.YYYY, and you just wand MM-DD-YYYY instead, then you don't have to deal with any datetime conversions. You can just do a substitution on the string:
>>> from datetime import datetime
>>> mydatestrings = ['05.01.2017','05.02.2017','05.03.2017']
>>> newdates = [ d.replace('.','-') for d in mydatestrings ]
>>> print(newdates)
['05-01-2017', '05-02-2017', '05-03-2017']
On the other hand, if you really want to get all of your dates as 'datetime' objects in Python, you can make a new list like this:
>>> datetime_objs = [ datetime.strptime(d, '%m.%d.%Y') for d in mydatestrings ]
Then format it however you need to:
>>> print(datetime_objs[1].strftime('%m-%d-%Y'))
05-02-2017
>>> print(datetime_objs[1].strftime('%b, %d %Y'))
May, 02 2017

Related

Python how to convert datetime.date to the YYYY-MM-DD? [duplicate]

This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 8 months ago.
I have a two million timestamp data. I am trying to find first and last date that to in the YYYY-MM-DD format so I can use them in saving file name. But, I found out that np.unique(df.index) is fast (10s) and produces dates in the
datetime.date(2022, 6, 7) format but df.index.strftime('%Y-%m-%d').unique() gives the output I want but it takes more than 5 min, which is bad. So, I decided to use the former approach.
So, How do I convert something like datetime.date(2022, 6, 7) to'2022-06-07'?
Just put that into the str(...) function:
import datetime
my_date = datetime.date(2022, 6, 7)
print(str(my_date)) # prints 2022-06-07
Technically, you can just print it and not make it a string first. But putting it in str means that instead of printing it, you could save that string to a variable.
If you need more advanced formatting options, then you can do what #FObersteiner suggested. But the format you want happens to be the default, so this will do if you just want that one format
Try this:
# import datetime module
from datetime import datetime
# consider date in string format
my_date = "30-May-2020-15:59:02"
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))

Convert date string format to a datetime Python Object [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
i've one doubt.
I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:
{"date":"2020-08-24T21:15:00+00:00"}
I want to get a python datetime object.
How can I do that?
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Use dateutil.parser which smartly parse date string:
import json
import dateutil.parser
result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])
# 2020-08-24 21:15:00+00:00
print(dt)
# <class 'datetime.datetime'>
print(type(dt))
I think you can do it respecting the format while parsing the string:
You have to try to follow the structure of the string and assign each value to the correct time value. For example:
str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
Note that your case is pretty different.
It could be similar to '%Y-%m-%dT%H:%M:%S.f'

How to subtract days from a date using datetime [duplicate]

This question already has answers here:
How to perform arithmetic operation on a date in Python?
(2 answers)
Closed 2 years ago.
Something surely extremely simple, but I've been browsing around for almost one hour and couldn't find:
Working with Python, I have a date d="2020-01-22" (means January, 22nd, 2020) and I want to calculate the date corresponding to d - 57 days. With datetime, surely, but how, exactly?
Use the following code-
from datetime import datetime, timedelta
d = datetime.today()
new_d = d - timedelta(days=57)
Use package datetime.
# python3
import datetime
d = datetime.datetime.strptime("2020-01-22", '%Y-%m-%d')
print(d - datetime.timedelta(days=57)) # 2019-11-26 00:00:00
You can use datetime.strptime. this is the main function for parsing strings into datetimes. It can handle all type of formats, with the format determined by a format string you provide. You can read in detail here
from datetime import datetime
date_time= datetime.strptime('2020-01-22", '%Y-%m-%d')
print(date_time)

Convert year from unicode format to python's datetime format

I have only year parameter as input in the following manner:
2014,2015,2016
I want to convert each element from my list into python's datetime format. Is it possible to do this kind of things if the only given parameter is the year ?
Just set month and day manually to 1
from datetime import date
YearLst = [2014,2015,2016]
map(lambda t: date(t, 1, 1),YearLst)

get year from string '07-JUL-50' [duplicate]

This question already has answers here:
2 digit years using strptime() is not able to parse birthdays very well
(3 answers)
Closed 9 years ago.
I have a birth date field like:
date = '07-JUL-50'
and when I wanna get the year I got this:
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
>>> my_date.year
2050
Is there an elegant way of get '1950'??
Thx
Documentation says that:
When 2-digit years are accepted, they are converted according to the
POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and
values 0–68 are mapped to 2000–2068.
That's why you are seeing 2050.
If you want 1950 instead, it depends on what are allowed dates in your particular scenario. E.g. if date values can be only dates in the past, you can do something like this:
import datetime
def get_year(date):
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
now = datetime.datetime.now()
if my_date > now:
my_date = my_date.replace(year=my_date.year - 100)
return my_date.year
print get_year('07-JUL-50') # prints 1950
print get_year('07-JUL-13') # prints 2013
print get_year('07-JUL-14') # prints 1914
Hope that helps.

Categories