I have a date in the format 2012-01-01 06:00:00. I want to get only the date in the format 2012-01-01.
I've tried multiple links such as Converting (YYYY-MM-DD-HH:MM:SS) date time
But, I could not find the solution.
Parse. str -> date.
from datetime import datetime
s = "2012-01-01 06:00:00"
dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
Format. date -> str.
s_ymd = dt.strftime("%Y-%m-%d")
Result:
>>> s_ymd
'2012-01-01'
Assuming your date is a string, the following works fine:
str = "2012-01-01 06:00:00"
print(str[:10])
The notation [:10] basically means "take first 10 characters of the string".
Related
I have the following string 20211208_104755, representing date_time format. I want to convert it to the python datetime format using datetime.strip() method.
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%y/%m/%d')
However I am getting the following error.
ValueError: time data '20211208' does not match format '%y/%m/%d'
The second argument in strptime has to match the pattern of your datetime string. You can find the patterns and their meaning on https://docs.python.org/3/library/datetime.html
In your case, you can format it as
from datetime import datetime
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print(datetime_object)
>>> 2021-12-08 10:47:55
what should work is to define how the mydatetime string is composed.
example:
%Y is the year (4 digits); check here for format (section strftime() Date Format Codes)
So in your example I would assume it's like this:
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print (datetime_object)
result
2021-12-08 10:47:55
and
type(datetime_object)
datetime.datetime
I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02
How to convert a date format (YYYY-MM-DD) to (YYYY,MM,DD) in Python
OR, I have a date = 2020-06-11 which I want to convert into seconds.
Works: d2 = (dt.datetime(2020,6,30) - t0).total_seconds()
Fails: d2 = (dt.datetime(2020-6-30) - t0).total_seconds()
How do I do it ?
If you need to cast a string to a datetime object, you can use strptime for this.
from datetime import datetime
t = datetime.strptime('2020-06-11', '%Y,%m,%d')
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
I using:
s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')
I need convert a number in date format (2020-01-13)
but when I print final:
2020-01-13 00:00:00
Tried datetime.date(s, '%Y%m%d') but It's returns a error:
an integer is required (got type str)
Is there any command to get only date without hour?
Once you have a datetime object just use strftime
import datetime
d = datetime.datetime.now() # Some datetime object.
print(d.strftime('%Y-%m-%d'))
which gives
2020-02-20
You can use strftime to convert back in the format you need :
import datetime
s = "20200113"
temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00
final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13
Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.
s = "20200113"
year = int(s[:4]) # 2020
month = int(s[4:6]) # 1
day = int(s[6:8]) # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'
You can also convert directly via strings.
>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'
You can use .date() on datetime objects to 'remove' the time.
my_time_str = str(final.date())
will give you the wanted result
I have a list of date time strings like this.
16-Aug-2019
I want to convert the string to 2019-08-01 this date format, and I have tried on this code , but it's getting me an error.
formatd_date = datetime.strptime(formatd_date, '%y-%m-%d')
ValueError: time data 'As-of' does not match format '%y-%m-%d'
If any can help, it will be huge thank.
Convert to datetime format and then convert to string format you want to:
>>> from datetime import datetime
>>> a = "16-Aug-2019"
>>> datetime.strptime(a, "%d-%b-%Y").strftime("%Y-%m-%d")
'2019-08-16'
Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Just fails because %y is 2-digit year. Use %Y for 4-digit year.