Python: Convert string into date format [duplicate] - python

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I know this has been asked a few times, but my scenario is a little different... The objective I need to accomplish is to convert a string of digits '20150425' (which happens to be a date), into a date format such as, '2015-04-25'. I need this because I am trying to compare date objects in my code, but have one variable type represented as a string.
Example below:
date = '20150425' ## want to convert this string to date type format
# conversion here
conv_date = '2015-04-25' ## format i want it converted into
Hope this is clear. Should not be difficult, just do not know how to do it.

This works
from datetime import datetime
date = '20150425'
date_object = datetime.strptime(date, '%Y%m%d')
date_object
>>> datetime.datetime(2015,4,25,0,0)

Assuming the date strings will always be 8 characters:
date = '20150425'
fdate = "{}-{}-{}".format(date[0:4], date[4:6], date[6:]) # 2015-04-25
Alternatively, you can go the "heavier" route and use the actual datetime class:
from datetime import datetime
date = '20150425'
dt = datetime.strptime(date, "%Y%m%d")
dt.strftime("%Y-%m-%d") # 2015-04-25

Related

Convert number string to weekday [duplicate]

This question already has answers here:
Converting date/time in YYYYMMDD/HHMMSS format to Python datetime
(3 answers)
How do I get the day of week given a date?
(30 answers)
Closed last month.
How do I convert 20230102 to Monday?
Using python, I need to accomplish this. I have a column of numbers in the format yyyymmdd.
Parse with strptime and format with strftime:
>>> from datetime import datetime
>>> n = 20230102
>>> datetime.strptime(str(n), "%Y%m%d").strftime("%A")
'Monday'
See strftime() and strptime() Format Codes for documentation of the % strings.
You can convert number string into weekday using "datetime" module
import datetime
def get_weekday(date):
date = datetime.datetime.strptime(date, '%Y%m%d')
return date.strftime('%A')
print(get_weekday('20230102'))
This is how you can achieve your desired output.
You can do it with weekday() method.
from datetime import date import calendar
my_date = date.today()
calendar.day_name[my_date.weekday()] #Friday

Python: How to convert a long datetime string to required format [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 4 months ago.
I have this time here : 2017-08-05T05:21:10.6582942Z
And I want to convert it into %Y-%m-%d %H:%M:%S
I can do that using some funky methods such as :
date = "2017-08-05T05:21:10.6582942Z"
new_date = date[:11] + " " + date[12:][:-9]
But is there any way I can do something cleaner with datetime or some libraries made for this specific purpose ?
Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:
from datetime import datetime as dt
date = '2017-08-05T05:21:10.6582942Z'
output = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S')
Output:
'2017-08-05 05:21:10'
Note:
The slice is needed to remove the last two characters from the string date, as the %f (fractional seconds) formatter only accepts six decimal values, and your string contains seven decimal values.
Per the formatting documentation:
%f: Microsecond as a decimal number, zero-padded to 6 digits.
Start with importing datetime:
import datetime as dt
Convert string to datetime object:
date = "2017-08-05T05:21:10.6582942Z"
new_date = dt.datetime.strptime(date[:-2], "%Y-%m-%dT%H:%M:%S.%f") # -2 slice to since %f only accepts 6 digits.
Format datetime object as string:
format_date = dt.datetime.strftime(new_date, "%Y-%m-%d %H:%M:%S") # returns your format
However, looking at your code it feels your date is already formatted and you don't require the last .strftime() usage.

How do I convert date and time string(1975-07-14T16:32:47.000Z) to Day-Month name-Year (14 July 1975) format in python [duplicate]

This question already has answers here:
How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]
(11 answers)
Closed 4 months ago.
I am writing a UI automated test that checks a date in the database and returns the date as a string in this format 1975-07-14T16:32:47.000Z and comparing it to the date that is displayed on the webpage but the date on the webpage is in this format Day-Month name-Year (14 July 1975), therefore I need to convert the date return by the database to Day-Month name-Year (14 July 1975) so that I am comparing like for like. How do I change the date string to the format I need
You can use dateutil.parser to parse the string you got from the datebase into a datetime.datetime, which in turn can be formatted using strftime:
import dateutil.parser
input="1975-07-14T16:32:47.000Z"
dt = dateutil.parser.parse(input)
print(dt.strftime("%d %B %Y"))
from datetime import datetime
dt_string = "1975-07-14T16:32:47.000Z"
datetime_object = datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S.%fZ")
new_datetime_string = datetime.strftime(datetime_object, "%d-%B-%Y")
print(new_datetime_string)
# prints "14-July-1975"
We are using datetime module where datetime.strptime will generate a datetime object where you can call .date(),.time(),.today() and other functions but to get back to string as per the given format of Day-Month Name-Year datetime.strftime()(stringify time) is used. This converts datetime obj to given format of datetime string.
%d - date (DD - 01,02,...,31)
%m - month (MM - 01,02,...,12)
%Y - Year (YYYY - 2022,2021,...)
%B - Full Month Name (January, Feburary,..)
%f - Milliseconds
you can find out more in following link: Datetime format codes

How to convert time to T Z format in python [duplicate]

This question already has answers here:
Generate RFC 3339 timestamp in Python [duplicate]
(7 answers)
Closed 2 years ago.
I would like to convert today's date to below format in python
What I tried:
>>> import datetime
>>> d_date = datetime.datetime.now()
>>> reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
>>> print(reg_format_date)
2020-08-04 06:40:52 PM
Expected format:
2017-10-18T04:46:53.553472514Z
can some one suggest please
Use utcnow() instead of now() to get the UTC time.
Use the isoformat() method. You'll need to add the trailing "Z" yourself.
In summary:
from datetime import datetime
reg_format_date = datetime.utcnow().isoformat() + "Z"
Here's how to get the current UTC time and convert to the ISO-8601 format (which is what your example shows). The timezone is hardcoded to Z.
import datetime
datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat() + 'Z'

Changing datetime format [duplicate]

This question already has answers here:
Convert Pandas Column to DateTime
(8 answers)
Closed 3 years ago.
I want to concatenate two dataframes, but they each have two columns that are datetime objects. One is formatted YYYY-MM-DD HH:mm:SS while in the other dataframe it is formateed MM/DD/YEAR HH:mm:SS. Is there way I can convert one format to the other, I am not picky on which one I end up with in the end.
start_time
2018-12-31 23:59:18
and
start_time
4/1/2017 00:13:24
Thanks!
You can convert the format like this
import datetime
date_time_str = '2018-12-31 23:59:18'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
date_time_str2 = date_time_obj.strftime('%d/%m/%Y %H:%M:%S')
print(date_time_str2)
Output :
31/12/2018 23:59:18

Categories

Resources