Date and time ⇔ character string

From time_struct to a string, or from a string to time_struct.

python


>>> import time
>>> now = time.localtime()
>>> now
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=0)

>>> str_now = time.strftime('%c', now)
>>> str_now
'05/08/12 04:03:42'
>>> time.strptime(str_now, '%c')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

>>> str_now = time.strftime('%Y/%m/%d %H:%M:%S', now)
>>> str_now
'2012/05/08 04:03:42'
>>> datetime.datetime.strptime(str_now, '%Y/%m/%d %H:%M:%S')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

The format strings for time.strftime () and time.strptime () are Documentation. It seems to be the same as C language.

Others It seems that time.asctime () makes the format the same as asctime () in C language, but there seems to be no way to convert this string to struct_time.

python


>>> asctime = time.asctime()
>>> asctime
'Tue May  8 04:03:42 2012'
>>> time.strptime(asctime, '%a %b %d %H:%M:%S %Y')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

I can't tell the difference between time and datetime, but I feel that time is fine if you don't add or subtract dates.

Recommended Posts

Date and time ⇔ character string
Get date and time in specified format
Character range / character string range
Pytest Current time test (fixed date and time)
To represent date, time, time, and seconds in Python
Hexadecimal string and string conversion
[Python2] Date string-> UnixTime-> Date string
Convert timezoned date and time to Unixtime in Python2.7
Extract "current date only" and "current date and time" with python datetime.
Convert date timezone (time difference) in Python (from string)
[python] Convert date to string
3-3, Python strings and character codes
Python indentation and string format
Remove double-byte spaces before and after the character string (python)
[Python] Create a date and time list for a specified period
BLAST result-like character string display
I want to convert an ISO-8601 character string to Japan time
Get the current date and time in Python, considering the time difference
Pandas basics for beginners ④ Handling of date and time items
String date manipulation in Python
Python f character (formatted string)
Story of speed comparison of sort of numerical value and character string (unfinished))
Is it a character string operation?
About time series data and overfitting
python string processing map and lambda
Time sorted by REAPER and labeled
[Python] How to change character string (str) data to date (strptime of datetime)
How to stop a program in python until a specific date and time