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

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"))

Related

How do I get rid of the year, month, and day? [duplicate]

This question already has answers here:
Compare only time part in datetime - Python
(3 answers)
Closed 1 year ago.
I was trying to write a program that converts a string to datetime type. The code looks like this.
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p)
and the output was
1900-01-01 20:36:00
How do I get rid of the '1990-01-01' ?
It's unfortunate that you cannot simply write
p = datetime.time.strptime(time, "%H:%M")
because time.strptime is not defined. You are forced to use datetime.strptime, which returns a datetime object no matter what fields are actually being parsed.
On the plus side, you can get the time object you want relatively easily.
t = p.time()
print(t) # Outputs 20:36:00
You're creating a datetime object from your string and displaying the datetime as a whole.
What you should do:
display just the time part:
use strftime:
The code
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.strftime("%H:%M"))
use time:
The code:
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.time())
What you really should do:
Create a time object from your data. For that you can use datetime.time
import datetime
time="20:36"
hour, minute = time.split(":")
t = datetime.time(hour=int(hour), minute=int(minute))
print(t)

How to encode time strptime format [duplicate]

This question already has answers here:
Detecting date format and converting them to MM-DD-YYYY using Python3
(3 answers)
Closed 3 years ago.
I have a python code for time.strptime and the format is like this:
start_date = time.strptime('2019-03-25', '%Y-%m-%d')
But now if my users try to input the time that is not according to the format it will give an error.
Let's say if users try to input the date format like this:
start_date = time.strptime('25-03-2019', '%Y-%m-%d')
That will give an error message
ValueError: time data '25-03-2019' does not match format '%Y-%m-%d'
So, how to encode the string to automatically give to the format the server provide..?
While there will always be cases that are ambiguous, you can use dateutil (python-dateutil on pypi) to parse dates from most standard formats:
>>> import dateutil
>>> dateutil.parser.parse('25-03-2019')
datetime.datetime(2019, 3, 25, 0, 0)
# ^ ^ ^
# year, month, day

Convert a series of string to date [duplicate]

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

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)

how to convert format of date to 'os.utime()' format [duplicate]

This question already has an answer here:
Python converting datetime to be used in os.utime
(1 answer)
Closed 6 years ago.
I'm trying to convert an ordinal dateTime value into a value that can be accepted by os.utime()
My date has the format: 201642322295
(which is: year=2016, month=4, day=23, hour=22, minute=29, second=5)
However, the method won't accept this and I'm not sure how to/ what to convert it into. I've tried converting it into a datetime also but this does not work.
The code segment:
s = int(self.newTime)
date = datetime(year=s[0:4], month=s[4], day=s[5:2], hour=s[8:2], minute=s[10:2], second=s[12])
os.utime(self.fileName, (date,date))
(I had tried using just the ordinal format, which modifies the datetime of the file but is not at all correct)
edit: This is not the same as 'python converting datetime to be used in os.utime' because it's using a completely different format
os.utime expects values in the form of integers representing a untix timestamp.
s = int(self.newTime)
date = datetime(year=s[0:4], month=s[4], day=s[5:2], hour=s[8:2], minute=s[10:2], second=s[12])
utime = time.mktime(date.timetuple())
os.utime(self.fileName, (utime, utime))

Categories