How to fix date formatting using python3 - python

I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?

>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.

This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.

Related

Timestamp to iso

I have a dataframe with timestamp of different formats one with 05-28-2022 14:05:30 and one with 06-04-2022 03:04:13.002 both I want to convert into iso format how can I do that?
input output
05-28-2022 14:05:30 -> 2022-05-28T14:05:30.000+0000
06-04-2022 03:04:13.002 -> 2022-06-04T03:04:13.002+0000
You can use strptime() + strftime(). Here is an example:
from datetime import datetime
import pytz
# parse str to instance
first = datetime.strptime('05-28-2022 14:05:30', '%m-%d-%Y %H:%M:%S')
first = first.replace(tzinfo=pytz.UTC)
print(first.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
print(f'{first.isoformat()}')
second = datetime.strptime('06-04-2022 03:04:13.002', '%m-%d-%Y %H:%M:%S.%f')
second = second.replace(tzinfo=pytz.UTC)
print(second.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))
print(second.isoformat())
# 2022-05-28T14:05:30.000000+0000
# 2022-05-28T14:05:30+00:00
# 2022-06-04T03:04:13.002000+0000
# 2022-06-04T03:04:13.002000+00:00
See datetime docs. Also you can use other packages for dates processing / formatting:
iso8601
pendulum
dateutil
arrow
Example with dataframe:
import pandas as pd
import pytz
from datetime import datetime
df = pd.DataFrame({'date': ['05-28-2022 14:05:30', '06-04-2022 03:04:13.002']})
def convert_date(x):
dt_format = '%m-%d-%Y %H:%M:%S.%f' if x.rfind('.', 1) > -1 else '%m-%d-%Y %H:%M:%S'
dt = datetime.strptime(x, dt_format).replace(tzinfo=pytz.UTC)
return dt.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
df['new_date'] = df['date'].apply(convert_date)
print(df)
date new_date
0 05-28-2022 14:05:30 2022-05-28T14:05:30.000000+0000
1 06-04-2022 03:04:13.002 2022-06-04T03:04:13.002000+0000

How to convert a date string zone oriented and hour string into datetime

I have two strings one: date='2021-12-30T23:00Z' where Z means UTC timezone and 23:00 means hour. I also have an hour string hour='3'. What I want is to convert date to datetime object and add this hour string to date as a delta. In result I would get a datetime object with hour: '2021-12-31T02:00Z' I tried function datetime.datetime.fromisoformat() with no luck.
Use strftime with their format.
from datetime import datetime, timedelta
date='2021-12-30T23:00Z'
date = datetime.strptime(date, '%Y-%m-%dT%H:%MZ')
new_date = date + timedelta(hours=3)
new_date = new_date.strftime('%Y-%m-%dT%H:%MZ')
print(new_date)
Output:
2021-12-31T02:00Z
You could do something like this:
from datetime import datetime
from datetime import timedelta
date = "2021-12-30T23:00Z"
hour = "3"
d = datetime.strptime(date, "%Y-%m-%dT%H:%M%z") + timedelta(hours=int(hour))
print(d)
output:
2021-12-31 02:00:00+00:00

changing datetime format from date to date time

I have a list of dates stored as strings. I need to convert them to this format "%Y%m%d %H:%M:%S %Z"
I can not achieve this since the date stored as a string has no time, just the date. eg. 2015-06-12
below is one iteration of the code/idea i tried but failed. any suggestions are greatly appreciated!
d = "2015-06-12"
x = datetime.datetime.strptime(d, "%Y-%m-%d").date()
x = datetime.date(x) + datetime.time(10, 23)
print(x)
You can use datetime.replace():
from datetime import datetime
d = "2015-06-12"
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23)
To print it in desired format you can use datetime.strftime():
print(x.strftime("%Y%m%d %H:%M:%S %Z"))
BUT it won't print timezone name (%Z), cause created datetime object has no information about timezone. You can add it manually, by providing time delta between UTC and timezone:
from datetime import datetime, timezone, timedelta
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23,
tzinfo=timezone(timedelta(hours=6), name="CST"))
Or set local timezone:
x = datetime.strptime(d, "%Y-%m-%d").replace(hour=10, minute=23,
tzinfo=datetime.utcnow().astimezone().tzinfo)

How can I transform my time to string and get only the part I need?

from datetime import datetime, timedelta
api_time = datetime.strptime(parsed_json["result"]["parameters"]["time"], "%H:%M:%S")
What I'm getting in api_time after debugging is 900-01-01 12:30:22. What I want is 12:30:22 only. I have checked other docs and .strptime should have done it but it didn't work.
Method 1: Strip space
One quick solution, if your input doesn't change.
from datetime import datetime, timedelta
api_time = datetime.strptime("1900-01-01 12:30:22".split(" ")[1], "%H:%M:%S")
print api_time
>1900-01-01 12:30:22
In your case:
api_time = datetime.strptime(parsed_json["result"]["parameters"]["time"], "%H:%M:%S")
Method 2: Construct datetime
Or you can just construct your datetime object and then access it's second, minute, hour attributes as follows:
from datetime import datetime, timedelta
api_time = datetime.strptime("1900-01-01 12:30:22", "%Y-%m-%d %H:%M:%S")
print "{0}:{1}:{2}".format(api_time.second, api_time.minute, api_time.hour)
>22:30:12
You can convert them from datetime to string, then just use string split:
a = '1900-01-01 12:30:22'
a.split(' ')[1]
-->
from datetime import datetime
api_time = datetime(1900, 01, 01, 12, 30, 22).strftime("%Y-%m-%d %H:%M:%S")
api_time.split(' ')[1]

Python convert datetime string to date

I have this string (It's come from a variable. as a example, st_date)
'2015-01-28 03:00:00'
and I want to parse the date and convert to type:date
datetime.date 2015-01-28
from it.. How could I do that?
Use datetime.strptime() which takes two arguments, your date as a string and the format you want.
from datetime import datetime
my_date = datetime.strptime('2015-01-28 03:00:00', '%Y-%m-%d %H:%M:%S')
my_date.year
>> 2015
import datetime
import time
date_str_obj = '2015-01-28 03:00:00'
date_date_obj = datetime.datetime.strptime(date_str_obj, '%Y-%m-%d %I:%M:%f')
Just read the docs https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
from datetime import datetime
a = '2015-01-28 03:00:00'
print datetime.strptime(a[:10], '%Y-%m-%d')
Use the strptime() function.
datetime.datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %H:%M:%S') #24-hour clock
datetime.datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %I:%M:%S') #12-hour clock
You can use easy_date to make it easy:
import date_converter
my_date = date_converter.string_to_date('2015-01-28 03:00:00', '%Y-%m-%d %H:%M:%S')
from datetime import datetime
date = datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %H:%M:%S')
date.date()
Use dateutil:
import dateutil.parser
dateutil.parser.parse('2015-01-28 03:00:00').date()
>>datetime.date(2015, 1, 28)

Categories

Resources