0

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]
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
S_Star
  • 53
  • 5

2 Answers2

0

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
Geeths
  • 81
  • 7
  • dt1 should be a series of string dates, not only one string... dt = ['2022.12.31', '2022.11.30'.....] – S_Star Feb 07 '23 at 21:33
  • @S_Star if you are receiving your strings in a list - you need to tell us this in your question, we can't read your mind. – dafrandle Feb 07 '23 at 21:47
  • Thank you @Geeths for the effort! I will try your solutions as well. Meanwhile, I have tried the following solution and it worked: depoziti['ddospevanje'] = (depoziti['ddospevanje'].str.replace('.','-', regex = True).astype(str)) However, when I want to convert this column to datetime I got an error: value error: time data ""at position 274 doesn't match format specified – S_Star Feb 07 '23 at 22:17
0

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.

dafrandle
  • 78
  • 1
  • 8
  • Hi @dafrandle, thank you for your effort as well. I am working with a series of dates which are objects, not with one string and strftime() or strptime() are for string, not series. I found how to replace dots to '-'. Now I need to convert that series in datetime, but I got value error. – S_Star Feb 07 '23 at 22:19
  • @S_Star your question says you have strings, I'm not able to help further until you update your question to accurately say what you have. – dafrandle Feb 08 '23 at 00:32