How to convert datetime format? - python

I have datetime in yyyy-MM-dd'T'HH:mm:ssZ i.e (2022-04-30T07:00:00+0000) format and I want it to be converted into %Y-%m-%d i.e 2022-04-30 format in python. Can anyone tell me how to do it?
I have tried date = datetime.strptime(end_time, "%Y-%m-%d") and
date = datetime.strptime(end_time, "%Y-%m-%d").date(), but it's not working.

Related

extract date, month and year from string in python

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 change date format to another date format automatically

Currently I'm capturing dates from a csv file, but the date field can come in any format.
I want to transform this dates to only %Y-%m-%d date format. But with strptime does not work.
For example:
Csv Dates ----> Transformation
2020/06/23 06:00
---> 2020-06-23
23/04/2020 05:00
---> 2020-04-23
11/4/2020 10:00
---> 2020-04-11
2022/1/24 11:00
---> 2022-01-24
Code:
fecha_csv = row[7]
fecha_csv = datetime.strptime(fecha_csv, '%Y-%m-%d %H:%M:%S')
fecha_csv = fecha_csv.date()
This is assuming the format of dates that you have given in your example. to format further dates this may need to be modified depending on the date given.
the problem you are having possibly is that you aren't converting it into a proper datetime object so that you can change it to the date format that you would like.
you can change the date format with time into just the date with a couple of methods. one is to just do string manipulation if the date is always formatted the same like the examples shown or you could convert it to datetime objects like the following.
fecha_csv = row[7]
if len(fecha_csv.split('/')[0]) > 2: # year is first
datetime.strptime(fecha_csv, '%Y/%m/%d %H:%M').strftime("%Y-%m-%d")
else: # year is last
datetime.strptime(fecha_csv, '%d/%m/%Y %H:%M').strftime("%Y-%m-%d")
A problem with your current code is that it was formatted to read dates in as 2020-06-23 06:00:00 when it should only be formatted to read in as 2020/06/23 06:00
Similarly, you could use a date parser -
from dateutil.parser import parse
fecha_csv = row[7]
csv_date = parse(fetch_csv).date()

Get YYYY-DD-MM from YYYY-DD-MM HH:MM:SS

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

Unable to subtract a day from any specific date format

I'm trying to subtract a day from this date 06-30-2019 in order to make it 06-29-2019 but can't figure out any way to achive that.
I've tried with:
import datetime
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
print(date)
It surely gives me back the date I used above.
How can I subtract a day from a date in the above format?
try this
import datetime
date = "06/30/19"
date = datetime.datetime.strptime(date, "%m/%d/%y")
NewDate = date + datetime.timedelta(days=-1)
print(NewDate) # 2019-06-29 00:00:00
Your code:
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
Check type of date variable.
type(date)
Out[]: str
It is in string format. To perform subtraction operation you must convert it into date format first. You can use pd.to_datetime()
# Import packages
import pandas as pd
from datetime import timedelta
# input date
date = "06-30-2019"
# Convert it into pd.to_datetime format
date = pd.to_datetime(date)
print(date)
# Substracting days
number_of_days = 1
new_date = date - timedelta(number_of_days)
print(new_date)
output:
2019-06-29 00:00:00
If you want to get rid of timestamp you can use:
str(new_date.date())
Out[]: '2019-06-29'
use timedelta
import datetime
date = datetime.datetime.strptime("06/30/19" ,"%m/%d/%y")
print( date - datetime.timedelta(days=1))

Comparing two dates in different format with python

I have 2 dates defined as a strings. If I would know the original date format, I would compare it like this:
import time
date1 = "1/1/2013 12:00:00 AM" # formatted like "%m/%d/%Y %H:%M:%S %p"
date2 = "1/1/2016" # formatted like "%m/%d/%Y"
format1 = "%m/%d/%Y %H:%M:%S %p"
format2 = "%m/%d/%Y"
if time.strptime(date1, format1) > time.strptime(date2, format2):
pass
How can I compare it if I do not know the date format?
How can I compare it if I do not know the date format?
You can't.
Every comparison assumes that you know what you are comparing.
You can try to parse it with dateutil.parser.parse. This method parse a string in one of the supported formats. And then compare it.
datautil is a third-party module.

Categories

Resources