Convert string datetime to timestamp and vice verse in python [duplicate] - python

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I have a date stored as a string:-
16/07/2014 13:00:00
I want to convert this into timestamp.
Also from timestamp to this format again.
Please suggest the best possible way to do this in python.

You can use datetime to handle combined dates and times. You could parse this string using datetime.strptime but then you'd have to manually select the formatting.
Alternatively you can use the dateutil package which has a parser which can intelligently guess the string format and return a datetime object, as shown below:
from dateutil import parser
s = '16/07/2014 13:00:00'
d = parser.parse(s)
print(d)
# 2014-07-16 13:00:00
print(type(d))
# datetime.datetime

The documentation to look into this deeper is here
The functions you are looking for are time.strptime(string[, format]) to go from string to timestamp, and then from timestamp to string is time.strftime(format[, t])
Here is an example for your format:
>>> from datetime import datetime
>>>
>>> date_object = datetime.strptime('16/07/2014 13:00:00', '%d/%m/%Y %H:%M:%S')
>>> print date_object
2014-07-16 13:00:00
The to go back to your format (I have used gmtime() to get the current time to show you can convert any datetime to your desired format)
>>> from time import gmtime, strftime
>>> date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
>>> print date_string
17/09/2014 09:31:00

Your best bet is the datetime library: https://docs.python.org/2/library/datetime.html
import datetime
mytime='16/07/2014 13:00:00'
pythontime=datetime.datetime.strptime(mytime, '%d/%m/%Y %H:%M:%S')
stringtime=pythontime.strftime('%d/%m/%Y %H:%M:%S')
Enjoy!

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

Subtracting datetime in string format with datetime format

I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.
You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325
The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.

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'

Python: Convert string into date format [duplicate]

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

Change Date Format In Python [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 8 years ago.
I need to convert date string "Dec 17 00:00:06" to string "2014-12-17 00:00:06" in python. I looked at the datetime.strptime but still can't find a way for this.
eg:
Dec 17 00:00:06 to 2014-12-17 00:00:06
You can use datetime module.
For e.g.
>>> import datetime
>>> do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
We can replace year value to 2014 like following:
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%Y-%m-%d %H:%M:%S")
'1900-12-17 00:00:06'
>>> do1 = do.replace(year=2014)
>>> do1.strftime("%Y-%m-%d %H:%M:%S")
'2014-12-17 00:00:06'
If we want only time value then we can try like-
>>> do = datetime.datetime.strptime("Dec 17 00:00:06", "%b %d %H:%M:%S")
>>> do.strftime("%H:%M:%S")
'00:00:06'
Updated: update datetime string from file with its time string.
Algo:
Get content from the input text file.
Used re module i.e regular expression to get all pattern from content.
Use set method to remove duplicate values.
Convert datetime string to time string and update content.
Write new content into same file or other file.
code is:-
import datetime
import re
p = "/home/vivek/Desktop/input.txt"
with open(p, "rb") as fp:
content = fp.read()
date_values = set(re.findall("\[([^]]+)\]", content))
for i in date_values:
do = datetime.datetime.strptime(i, "%b %d %H:%M:%S")
content = content.replace("[%s]"%i, "%s"%(do.strftime("%H:%M:%S")) )
p = "/home/vivek/Desktop/output.txt"
with open(p, "wb") as fp:
fp.write(content)
Using datetime module will help you out.
from datetime import datetime
Firstly convert your date string to a datetime object by writing the line below.
date_obj = datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
Then convert that date object to a string.
date_obj.strftime("%Y-%m-%d %H:%M:%S")
You can change the parameters of the above strftime() function, and get different formats as per your requirments. Please follow python datetime
Here is the link to the options for the parameters which can be passed in the strftime() function parameter options
Go and play around as per your requirement.
from dateutil import parser
parser.parse('Dec 17 00:00:06').isoformat()
>>> '2015-12-17T00:00:06'

Categories

Resources