Convert Shell date format to Python date format - python

Can below piece of shell date format be converted to python date format?
date_used = $(date --date="$(date +%Y-%m-15) - 1 month" "+%Y_%m")
As per my understanding this above format is just taking day as 15 of current month and it simply subtracts 1 month and results in giving output in the format of year_month.
Output of the above shell date format -->
echo $date_used = 2022_05
Can this particular scenario be done using python?
Any update about it would be really appreciable.

An equivalent would be:
from datetime import datetime,timedelta
# Current date, replace date with 15, subtract 30 days and format
date_used = (datetime.now().replace(day=15) - timedelta(days=30)).strftime('%Y_%m')
print(date_used)
Output:
2022_05

You can use python's datetime module to do this
it has a function named strptime you can use to read date and time data with format code very similar to unix date format (or maybe its even same i'm not sure)
and strftime to output in a certain format as well
you can see the functions and the format code to see if there's any different on
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
Example code
from datetime import datetime, timedelta
date = datetime.strptime((datetime.now() - timedelta(days=30)).strftime("%Y-%m") + "-15", "%Y-%m-%d")
print(date)
print(date.strftime("%Y_%m"))
output
2022-05-15 00:00:00
2022_05

Related

How do I delete year month and date, display only time on python

I have to convert the object to DateTime. However, it shows a year, month, and day at the front. So how can I display only time?
f1['Time'] = pd.to_datetime(f1['Time'], format = '%H:%M:%S.%f')
f1['Time']
It shows:
0 1900-01-01 01:32:03.897
1 1900-01-01 02:02:34.598
2 1900-01-01 01:34:31.421
What I want is time only, like this:
0 01:32:03.897
1 02:02:34.598
2 01:34:31.421
For 24h format :
print(datetime.datetime.now().strftime("%X"))
For 12h formart with am/pm :
print(datetime.datetime.now().strftime("%I:%M:%S %p"))
Please include your code in your post and not in a screenshot.
But also, did you try using
datetime.time
It seems that you're successfully converting the data to datetime objects. What is being shown in the output is the string representation of the date.
The format string you passed to pd.to_datetime is just for parsing the dates. It does not affect their internal data. If you only need strings, you should call .strftime("%H:%M:%S.%f") for each date object in your collection.

what is this time format: XX:XX.X, and how to transfer it to usual year-month-day-hour-minute-second in Python

I have some date data like:
46:53.4
57:00.0
51:50.9
53:13.9
What is this time format? And how to transfer it to the usual year-month-day-hour-minute-second in Python?
Code:
import datetime
#Input Date String
t = "46:53.4"
#Return a datetime corresponding to date string
dateTimeObject = datetime.datetime.strptime(t, '%M:%S.%f')
print (dateTimeObject)
Result:
1900-01-01 00:46:53.400000
I suppose 46:53.4 means forty-six minutes and fifty-three-point-four seconds.

how to get only date if we have taken date and time both in python

I have a csv file which contains a date format like: 12/10/2011:02:03:20. I have more than 10 data of date/time from which I only want to read like: 12/10/2011 for that I have read the csv file name code written to give the date is: row[5] is the column of my date/time.
Date=row[5];
df= datetime.datetime(Date)
df.strftime('%m/%d/%Y')
but it's giving the error:
TypeError: an integer is required (got type str)
Please help me how to do it
from datetime import datetime
d = '12/10/2011:02:03:20'
dt = datetime.strptime(d, "%d/%m/%Y:%H:%M:%S")
print(dt.date())
A reference of all the legal format codes:
Directive - Description - Example
%d Day of month 01-31 (12 here)
%m Month as a number 01-12 (10 here)
%Y Year, full version (2011 here)
%H Hour 00-23 (02 here)
%M Minute 00-59 (03 here)
%S Second 00-59 (20 here)
For more references : Click here - Python Datetime
Use strptime to convert to datetime object then use strftime
Ex:
import datetime
df= datetime.datetime.strptime("12/10/2011:02:03:20", "%d/%m/%Y:%H:%M:%S")
print(df.strftime('%m/%d/%Y'))
Output:
10/12/2011
Use strptime(), examples in doc.
See https://docs.python.org/2/library/datetime.html

Python - How to convert datetime data using toordinal considering the time

Let's assume that I have the following data:
25/01/2000 05:50
When I convert it using datetime.toordinal, it returns this value:
730144
That's nice, but this value just considers the date itself. I also want it to consider the hour and minutes (05:50). How can I do it using datetime?
EDIT:
I want to convert a whole Pandas Series.
An ordinal date is by definition only considering the year and day of year, i.e. its resolution is 1 day.
You can get the microseconds / milliseconds (depending on your platform) from epoch using
datetime.datetime.strptime('25/01/2000 05:50', '%d/%m/%Y %H:%M').timestamp()
for a pandas series you can do
s = pd.Series(['25/01/2000 05:50', '25/01/2000 05:50', '25/01/2000 05:50'])
s = pd.to_datetime(s) # make sure you're dealing with datetime instances
s.apply(lambda v: v.timestamp())
If you use python 3.x. You can get date with time in seconds from 1/1/1970 00:00
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()

how to subtract date from date from sql in python

I run a sql query that returns a date in the format '2015-03-01T17:09:00.000+0000' I want to subtract this from today's date.
I am getting today's date with the following:
import datetime
now = datetime.datetime.now()
The formats don't seem to line up and I can't figure out a standardize format.
You can use strptime from datetime module to get python compatible date time from your query result using a format string. (You might have to play with the format string a bit to suit your case)
ts = '2015-03-01T17:09:00.000+0000' to a format string like
f = '%Y-%m-%dT%H:%M:%S.%f%z'
date_from_sql = datetime.datetime.strptime(ts, f)
now = datetime.datetime.now()
delta = date_from_sql - now
The .000 is probably microseconds (denoted by %f in the format string) and the +0000 is the utc offset (denoted by %z in the format string). Check this out for more formatting options: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
Check out this thread for an example: what is the proper way to convert between mysql datetime and python timestamp?
Checkout this for more on strptime https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
Getting the delta between two datetime objects in Python is really simple, you simply subtract them.
import datetime
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()
delta = d2 - d1
print delta.total_seconds()
d2 - d1 returns a datetime.timedelta object, from which you can get the total second difference between the two dates.
As for formatting the dates, you can read about formatting strings into datetime objects, and datetime objects into string here
You'll read about the strftime() and strptime() functions, and with them you can get yourself two datetime objects which you can subtract from each other.

Categories

Resources