Getting Python to print pretty date strings? - python

How can I get Python to output
'Mon Jun 04'
'Tue Jun 05'
etc, for a week of given time?
ex
today = datetime.datetime.today()
### do some magic
days = ['Tue Jun 05',...]
What do I do with 'today' to generate the results? I'm not even sure if I'm the right module, calender seems to share similar features.

days = [today.strftime("%a %b %y"), ...]
We use strftime to take a datetime object and format it to a string
http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

Look at the strftime method of datetime objects.

Related

How do I Change Text to Date/Time and then Format in Python 3

For a course I am taking, we have a tab delimited flat file that I am importing into Python 3 using a Jupyter Notebook. The format of the date time is below and again it is currently a text string.
Sat Jul 25 04:43:04 +0000 2020
How do I change this from text to a date/time in Python 3?
How do I change the date/time format to be: YYYY-MM-DD HH:MM?
Thanks,
Use the datetime standard module:
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime
Example:
import datetime
s = 'Sat Jul 25 04:43:04 +0000 2020'
dt = datetime.datetime.strptime(s, '%a %b %d %H:%M:%S %z %Y')
string = dt.strftime('%Y-%m-%d %H:%M') # -> 2020-07-25 04:43
from datetime import *
test = 'Sat Jul 25 04:43:04 +0000 2020'
year = test[-4:]
month = test[4:7]
day = test[8:10]
time = test[12:19]
adjusted_date = f'{day}-{month}-{year}-{time}'
x = datetime.strptime(adjusted_date, "%d-%b-%Y-%H:%M:%S")
z = datetime.strftime(x, "%d-%m-%Y-%H:%M")
print(z)
OUTPUT:
2020-07-25 04:43
The easiest way I could think about right now. Hope that helps and answers your question.
Before anyone complains. User asking question is definitely new to programming. Reading docs etc it is like a black magic when you just started, all this %Y%M%D means nothing :D so above it is (imo) the most easy to understand way of doing it, self-explanatory.. and if someone is struggling with slicing.. then it should go back and learn it.

Convert different date strings to unix timestamp in python 3.6

I have two strings. How can I convert them to UNIX timestamp (eg.: "1284101485")? (Please observe that 1284101485 is not the correct answer for this case.)
I don't care about time zones as long as it is consistent.
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
You can use dateparser
Install:
$ pip install dateparser
Sample code:
import dateparser
from time import mktime
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
datetime1 = dateparser.parse(string_1_to_convert)
datetime2 = dateparser.parse(string_2_to_convert)
unix_secs_1 = mktime(datetime1.timetuple())
unix_secs_2 = mktime(datetime2.timetuple())
print(unix_secs_1)
print(unix_secs_2)
Output:
1561492438.0
1561488838.0
The above implementation gives you a consistent response and doesn't give you an error when trying to parse CEST.
you can use .strptime to parse by a format you specify.
try this:
import datetime
string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'
ts1 = datetime.datetime.strptime(string_1_to_convert, "%a %b %d %H:%M:%S %Z %Y").timestamp()
ts2 = datetime.datetime.strptime(string_2_to_convert, "%Y-%m-%d %H:%M:%S").timestamp()
print(ts1)
print(ts2)
NOTICE: the CEST part might be non-portable, as strptime only knows how to parse timezones that appear in time.tzname.

Python Date / Time Regular Expression

I am pretty new to regular expressions and it's pretty alien to me. I am parsing an XML feed which produces a date time as follows:
Wed, 23 July 2014 19:25:52 GMT
But I want to split these up so there are as follows:
date = 23/07/2014
time = 19/25/52
Where would I start? I have looked at a couple of other questions on SO and all of them deviate a bit from what I am trying to achieve.
Use datetime.strptime to parse the date from string and then format it using the strftime method of datetime objects:
>>> from datetime import datetime
>>> dt = datetime.strptime("Wed, 23 July 2014 19:25:52 GMT", "%a, %d %B %Y %H:%M:%S %Z")
>>> dt.strftime('%d/%m/%Y')
'23/07/2014'
>>> dt.strftime('%H/%M/%S')
'19/25/52'
But if you're okay with the ISO format you can call date and time methods:
>>> str(dt.date())
'2014-07-23'
>>> str(dt.time())
'19:25:52'

Twitter created_at convert epoch time in python

I have this date from Twitter:
created_at = "Wed Aug 29 17:12:58 +0000 2012"
I want to convert it to a time using something like:
time.mktime(created_at)
But I get this error:
TypeError: argument must be 9-item sequence, not str
What am I doing wrong?
You need to convert the incoming string to a Python time tuple using strptime before you can do anything with it.
This code will take the input string, convert it to a tuple and then converts that to a Unix-epoch time float using time.mktime:
import time
created_at = "Wed Aug 29 17:12:58 +0000 2012"
print time.mktime(time.strptime(created_at,"%a %b %d %H:%M:%S +0000 %Y"))
I don't if it too late, use arrow package instead could fewer imports and a lot less code.
pip install arrow
Then:
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y")
<Arrow [2012-08-29T17:00:58+00:00]>
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y").timestamp
1346259658
Read the documentation of time.mktime
It requires struct_time, or you can alternatively represent it using a 9-tuple.
The required entries are:
Year
Month
Date
Hour
Minute
Second
Day in week
Day in year
Daylight Savings Time
This is not the function you need, however. It seems that you want to use strptime instead.
According to the documentation:
Parse a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
So, you can do:
time.strptime(created_at)

String to datetime

I saved a datetime.datetime.now() as a string.
Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7],
'%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
You don't need to create an intermediate string.
You can go directly from a datetime to a string with strftime():
>>> datetime.now().strftime('%b %d %Y')
'Oct 08 2010'
There's no one-liner way, because of your apparent requirement of the grammatical ordinal.
It appears you're using a 2.6 release of Python, or perhaps later. In such a case,
datetime.datetime.strptime("2010-10-08 14:26:01.220000", "%Y-%m-%d %H:%M:%S.%f").strftime("%b %d %Y")
comes close, yielding
Oct 08 2010
To insist on '8th' rather than '08' involves calculating the %b and %Y parts as above, and writing a decimal-to-ordinal function to intercalate between them.

Categories