Concatenate and convert string to date in Python - python

I have a string ‘2022.10.31’ and I want to convert it to ‘2022-10-31’ and then to date.
This is the R code:
pr1$dotvoranje <- paste(substr(pr1$dotvoranje, 1, 4), substr(pr1$dotvoranje, 6, 7), substr(pr1$dotvoranje, 9, 10), sep = "-")
pr1$dotvoranje <- as.Date(pr1$dotvoranje)
I need to do the following code in Python I found that I need to use .join() , but I have a column with strings that I need to convert to dates.
I started with this code (but I do not know how to use .join here). But this line only substracted the first four rows of that column. And I need to take that column and replace "."with "-".
depoziti['ddospevanje'] = depoziti['ddospevanje'].loc[0:4] + depoziti['ddospevanje'].loc[5:7] + depoziti['ddospevanje'].loc[8:10]

I'm going to assume that by "then to date" you mean you want a datetime object.
It is not necessary to do string.replace() in order to create the datetime object.
The datetime object uses syntax like %Y to refer to a year and so we will be using that with the function strptime() to ingest the date.
import datetime
date_as_string = "2022.10.31"
date_format = "%Y.%m.%d"
date = datetime.strptime(date_as_string, date_format)
Now you have a date time object.
If you want to then print out the date as a string, you can use strftime()
new_format = "%Y-%m-%d"
date_as_new_string = date.strftime(new_format)
print(date_as_new_string)
Further reference:
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
https://www.w3schools.com/python/python_datetime.asp -(This also contains a list of all the syntax for use with strftime() or strptime())
if you are getting your dates (as strings) in a list, then just put the above code into a for loop:
import datetime
date_format = "%Y.%m.%d"
date_as_string_list = ['2022.12.31', '2022.11.30']
date_list = []
for date_as_string in date_as_string_list:
date_list.append(datetime.strptime(date_as_string, date_format))
now you have a list of datetime objects, and you can loop through them in order to get them as strings as already shown.

Just putting it together
from datetime import datetime
dt1 = '2022.10.31'
dt2 = datetime.strptime(dt1, '%Y.%m.%d').date()
print ("type(dt2) :", type(dt2))
print ("dt2 :", dt2)
Output
type(dt2) : <class 'datetime.datetime'>
dt2 : 2022-10-31
Update : dt1 should be a series of string dates, not only one string... dt = ['2022.12.31', '2022.11.30'.....]
If it's a list, use list comprehension
dt1 = ['2022.10.31', '2022.10.1', '2022.9.1']
dt2 = [datetime.strptime(i, '%Y.%m.%d').date() for i in dt1]
dt2
If it's a column in pandas dataframe, this is one way of doing it
df = pd.DataFrame({'event' : ['x', 'y', 'z'],
'date' : ['2022.10.31', '2022.10.1', '2022.9.1']})
df['date1'] = df['date'].apply(lambda x : datetime.strptime(x, '%Y.%m.%d').date())
df

Related

How to use parser on multiple time objects

I have an list:
list = ['2022-06-01', '2022-02-02']
Now am using parser to convert this to python date object. like this,
from dateutil import parser
def to_date(value):
for data in value:
return parser.parse(data)
Above one gives just one output, but i need the output for both the times and also need to convert that to an string like this:
From : June 1, 2022 | To: Feb. 28, 2022
Is that possible with parser ?
You only get one value back from your to_date function because you exit the function in the first loop iteration. You need to introduce an list storing your parsed dates temporary:
from dateutil import parser
def to_date(date_list):
parsed_date_list = []
for date in date_list:
parsed_date_list.append(parser.parse(date))
return parsed_date_list
date_list = ['2022-06-01', '2022-02-02']
res = to_date(date_list)
Or using a list comprehension to keep your code more concise:
from dateutil import parser
def to_date(date_list):
return [parser.parse(date) for date in date_list]
date_list = ['2022-06-01', '2022-02-02']
res = to_date(date_list)
And to format your string, simply use the strftime function as pointed out by kpie
in his comment:
# res = to_date(date_list)
date_format = "%b %d, %Y"
print(f"From: {res[0].strftime(date_format)} | To: {res[1].strftime(date_format)}")
Do not use list as a variable name. list is a data structure and therefore already in use by the class list.
You can use the standard datetime library to perform the parsing.
datetime.datetime.strptime allows you to convert a datetime string to a datetime object.
datetime.datetime.strftime allows you to convert a datetime object to the desired string.
dt_from, dt_to = [datetime.datetime.strptime(x, "%Y-%m-%d") for x in dt_list]
dt_str = f"From : {datetime.datetime.strftime('%b %d,%Y', dt_from)} | To: {datetime.datetime.strftime('%b %d,%Y', dt_to)}"]

How do I convert YYYYMMDD to datetime, but maintain the same format

I have an variable integer that is in the format YYYYMMDD.
How do i convert that variable to datetime while maintaining the format of YYYYMMDD?
date = 20200930
nextday = date + 1
How do i fix this, so the nextday variable displays as 20201001
If I'm understanding what you need to do correctly, you can easily do it using the datetime package.
First, convert your variable to a date:
import datetime
date = 20200930
dt = datetime.datetime.strptime(str(date), '%Y%m%d')
Now, when you print this, you will see:
datetime.datetime(2020, 9, 30, 0, 0).
You can then add a day to it:
dt_new = dt + datetime.timedelta(1)
And specify the format you want to see the new date variable in:
print ('{date: %Y%m%d}'.format(date=dt_new))
which will give:
20201001.

What is the quickest way to increment date string YYYY-MM-DD in Python?

In Pandas, I am using dates with string format YYYY-MM-DD
What is the quickest way to increment the date with the result in YYYY-MM-DD format?
d1 = '2018-02-10'
I want to increment it by 1 and get the result back as a string:
d1_inc = '2018-02-11'
Pure Python
You can use the datetime module, part of the standard library. There are 3 steps:
Convert string to datetime object via strptime.
Add a day via timedelta.
Convert resulting datetime object back to string via strftime.
Here's a demo:
from datetime import datetime, timedelta
x = '2017-05-15'
res = (datetime.strptime(x, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
Pandas
The equivalent steps can be performed using 3rd party Pandas:
x = '2017-05-15'
# choose some combination of below methods
res = (pd.Timestamp(x) + pd.DateOffset(days=1)).strftime('%Y-%m-%d')
res = (pd.to_datetime(x) + pd.Timedelta('1 day')).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
Using pd.to_datetime, pd.TimeDelta and strftime:
fmt = '%Y-%m-%d'
(pd.to_datetime(<your series or column>, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
Example
df = pd.DataFrame({'date': ['2017-04-02', '2017-04-23']})
fmt = '%Y-%m-%d'
>>> (pd.to_datetime(df.date, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
0 2017-04-03
1 2017-04-24
Name: date, dtype: object
You can perform arithmetic operations with datetime and timedelta objects.
from datetime import datetime, timedelta
d = datetime(year=2018, month=3, day=1)
t = timedelta(days=1)
d + t
# datetime.datetime(2018, 3, 2, 0, 0)
d + t + t
# datetime.datetime(2018, 3, 3, 0, 0)
for i in range(30):
d += 1
print(d)
# datetime.datetime(2018, 3, 31, 0, 0)
You mean like this
date = datetime.date(2015,5,15)
date += datetime.timedelta(days=1)
It depends on what you mean by quickest. I'm assuming you mean the quickest way to program this, not the shortest program execution time (which might be relevant when you're doing lots of these).
from datetime import datetime, timedelta
original_date = '2018-5-15'
print('The original date is {}, the date one day later is: {}'.
format(original_date, (datetime.strptime(original_date, '%Y-%m-%d') +
timedelta(days=1)).strftime('%Y-%m-%d')
Step by step version:
Create a datetime object from the string, note the string that shows python the formatting (see the documentation for more information)
dt = datetime.strptime(original_date, '%Y-%m-%d')
Add a day
dt += timedelta(days=1)
Reformat it back to the requested string
print(dt.strftime('%Y-%m-%d'))
That's all!

Split List based on index of value

Assuming I have a list of dates:
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
I want to split the 'dates' list based on this 'test' variable
Desired output:
1. ['11/09/2013','12/09/2013','20/09/2013']
2. ['27/09/2013','30/09/2013']
If 'test' actually belongs(contains) in the list, it must be in list 1.
I'm trying everything still no luck.
You should convert the strings into datetime objects and then split the list using a date comparison:
from datetime import datetime
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
# Convert to datetime objects
dd = [datetime.strptime(d,'%d/%m/%Y') for d in dates]
tt = datetime.strptime(test,'%d/%m/%Y')
# Split lists
dd_before = [d for d in dd if d < tt]
dd_after = [d for d in dd if d >= tt]
# Convert back to strings if needed
dates_before = [datetime.strftime(d,'%d/%m/%Y') for d in dd_before]
dates_after = [datetime.strftime(d,'%d/%m/%Y') for d in dd_after]
dates =['11/09/2013','12/09/2013','20/09/2013','27/09/2013','30/09/2013']
test = '21/09/2013'
dates.append(test)
dates.sort()
index = dates.index(test)
print dates[:index]
print dates[index + 1:]
output
['11/09/2013', '12/09/2013', '20/09/2013']
['27/09/2013', '30/09/2013']
You can get your desired result.
How about converting the items to datetime objects?
from datetime import datetime
# convert to datetime objects
datesdt = [datetime.strptime(date, '%d/%m/%Y') for date in dates]
testdt = datetime.strptime(test, '%d/%m/%Y')
# make separate datetime object lists for low and high dates
low_date_dt_list = [dt for dt in datesdt if dt <= testdt]
high_date_dt_list = [dt for dt in datesdt if dt > testdt]
# now print in desired format
low_date_list = [dt.strftime('%d/%m/%Y') for dt in low_date_dt_list]
high_date_list = [dt.strftime('%d/%m/%Y') for dt in high_date_dt_list]
Here's what I get for output when using the above code with your given dates and test values:
In [27]: low_date_list
Out[27]: ['11/09/2013', '12/09/2013', '20/09/2013']
In [28]: high_date_list
Out[28]: ['27/09/2013', '30/09/2013']
Documentation for datetime.strptime
Datetime Format Codes
Documentation for strftime

Date Time Formats in Python

What are these date-time formats? I need to convert them to the same format, to check if they are the same. These are just two coming from a separate data source, so I need to find a way to make them the same format. Any ideas?
2013-07-12T07:00:00Z
2013-07-10T11:00:00.000Z
Thanks in advance
That extra .000 is micro seconds.
This will convert a date string of a format to datetime object.
import datetime
d1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")
d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
Then convert them into any format depending on your requirement, by using:
new_format = "%Y-%m-%d"
d1.strftime(new_format)
perhaps use .isoformat()
string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z specifies "zulu" time or UTC.
You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
You can remove the microseconds by change the microseconds value to 0:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt
you can try to trim the string
data = "2019-10-22T00:00:00.000-05:00"
result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")
result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")
result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")
use datetime module.
For a variable
import datetime
def convertDate(d):
new_date = datetime.datetime.strptime(d,"%Y-%m-%dT%H:%M:%S.%fZ")
return new_date.date()
convertDate("2019-12-23T00:00:00.000Z")
you can change the ".date()" to ".year", ".month", ".day" etc...
Output: # is now a datetime object
datetime.date(2019, 12, 23)
For a DataFrame column, use apply()
df['new_column'] = df['date_column'].apply(convertDate)
* Short and best way:
str(datetime.datetime.now()).replace(' ','T')
or
str(datetime.datetime.now()).replace(' ','T') + "Z"

Categories

Resources